baojie
-
C++,
pasted
on Jun 18:
|
//11 Create a tree
//2011-06-18
#include <iostream>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
int cutoff = 8;
int counter = 0;
node *createNode(){
node *n = new node;
if (!n) return NULL;
n->left = NULL;
n->right = NULL;
//cout << counter <<"\n";
n->data = counter++;
return n;
}
void addChildren(node *n){
if (counter > cutoff) return;
node *l = createNode();
if(l) {
n->left = l;
}
node *r = createNode();
if(r) {
n->right = r;
}
addChildren(l);
addChildren(r);
}
void printTree(node *n, int level){
if(!n) return; int ld = -1, rd = -1;
if (n->left) ld = n->left->data;
if (n->right) rd = n->right->data;
cout.width(level*2);
cout.fill(' ');
cout << n->data << "->[" << ld << ", " << rd << "]\n";
printTree(n->left, level+1);
printTree(n->right, level+1);
}
int main(){
node *root = createNode();
addChildren(root);
printTree(root,0);
return 1;
}
|
Output:
|
0->[1, 2]
1->[3, 4]
3->[5, 6]
5->[7, 8]
7->[-1, -1]
8->[-1, -1]
6->[-1, -1]
4->[-1, -1]
2->[-1, -1]
|
|