用于搜索二叉树最大高度的递归代码

时间:2014-11-27 11:58:27

标签: c recursion binary-tree

我使用此代码创建了一个树(这是过时的,查看底部,更新问题):

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

然后尝试找到最大深度(函数Max和插入工作正常),使用:

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));
  }
}

它显示我最大深度为3的错误;我编译了C99标准。我在互联网的几个地方找到了这个和类似的代码,但这里不起作用,任何想法有什么不对?感谢..

建议添加插入代码:

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); 
  }
}

和newNode函数:

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

更新:  新的buildTree函数:

struct node* buildTree() {
  struct node* root = newNode(3);
  root->left = newNode(2);
  root->right = newNode(1);

  return(root);
} 

1 个答案:

答案 0 :(得分:0)

代码可以工作,但看起来你构建的树不是你的意思,可能是因为你不断地将一个新节点连接到前一个节点(而不是单个根节点)。 假设插入返回刚刚创建的节点,那么首先添加树节点2: 树:(2) 您正在添加树节点4作为树节点2的子节点: 树:(2)--(4) 最后,您将树节点10添加为树节点4的子节点: 树:(2)--(4)--(10)

因此,您可以看到树深度为3(包括根)。

相关问题