c - Recursive code for searching max height of binary tree -


i've created tree using code (this outdated @ bottom, problem updated):

struct node* buildtree() {   struct node* root = null;   root = insert(root, 2);   root = insert(root, 4);   root = insert(root, 10);   return(root); } 

then tried find max depth of (functions max , insert work properly), using this:

int maxheight(struct node* p) {   if(p == null) {return 0;}   else{     int leftdepth = 1 + maxheight(p->left);     int rightdepth = 1 + maxheight(p->right);     return(max(leftdepth, rightdepth));   } } 

and shows me error max depth 3; i've compiled in c99 standard. i've found , similar code in several places in internet, here doesn't work, ideas what's wrong? thanks..

as suggested adding insert code:

struct node* insert(struct node* node, int data) {   if (node == null) {     return(newnode(data));   }   else {     if (data <= node->data) node->left = insert(node->left, data);     else node->right = insert(node->right, data);     return(node);    } } 

and newnode function:

struct node* newnode(int data) {   struct node* node = malloc(sizeof(struct node));   node->data = data;   node->left = null;   node->right = null;   return(node); } 

update: new buildtree function:

struct node* buildtree() {   struct node* root = newnode(3);   root->left = newnode(2);   root->right = newnode(1);    return(root); }  

the code works looks tree built not meant, keep concatenating new node previous node (and not single root). assuming insert returns node created first add tree node 2: tree: (2) you're adding tree node 4 child of tree node 2: tree: (2)--(4) you're adding tree node 10 child of tree node 4: tree: (2)--(4)--(10)

so can see tree depth 3 (including root).


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -