简体   繁体   中英

Recursive code for searching max height of binary tree

I've created a tree using this code (this is outdated look at the 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 to find max depth of that (functions Max and 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 it shows me error like max depth is 3; I've compiled in C99 standard. I've found this and similar code in several places in the Internet, but here doesn't work, any 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 but it looks like the tree you built is not what you meant, probably as you keep concatenating a new node to the previous node (and not to the single root). Assuming the insert returns the node just created then your first add a tree node 2: Tree: (2) The you're adding a tree node 4 as a child of tree node 2: Tree: (2)--(4) Finally you're adding a tree node 10 as a child of tree node 4: Tree: (2)--(4)--(10)

So as you can see the tree depth is 3 (including the root).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM