【发布时间】:2017-08-21 08:41:26
【问题描述】:
我试图找到一棵树的高度。这是我在网上找到的一些代码。但是,我不明白它是如何工作的。如果您能解释一下这个程序是如何工作的,我将不胜感激。
#include <stdio.h>
#include <stdlib.h>
struct n {
int data;
struct n *left;
struct n *right;
};
typedef struct n node;
int height_of_tree(node *root) {
if (root == NULL) return -1; // Why doesn't the function break here?
int leftTree = height_of_tree(root->left);
int rightTree = height_of_tree(root->right);
if (leftTree > rightTree) return leftTree + 1;
else return rightTree + 1;
}
node *getNewNode(int data) {
node *newNode = (node *) malloc(sizeof(node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
node *insert(node *root, int data) {
if (root == NULL) root = getNewNode(data);
else if (data <= root->data)
root->left = insert(root->left, data);
else root->right = insert(root->right, data);
return root;
}
int main() {
node *root = NULL;
root = insert(root, 12);
root = insert(root, 23);
root = insert(root, 122);
root = insert(root, 1);
root = insert(root, 2);
root = insert(root, -3);
root = insert(root, -4);
printf("%d\n", root->right->data);
printf("%d\n", height_of_tree(root));
}
为什么height_of_tree 函数没有返回?
【问题讨论】:
-
我编辑了您的答案以使其更好。但是,我无法理解您所问的很多内容。如果我的编辑以您不希望的任何方式更改了您的原始问题,请告诉我。
-
原始问题没有改变,感谢您的编辑。你能解释一下这个程序是如何工作的吗?
-
如果您对程序的哪些部分您不了解,会更有帮助!
-
一个名为 height_of_tree 的函数。我不明白它是如何工作的
-
那么你理解 insert() 函数和 getNewNode() 对吗?
标签: recursion logic binary-search-tree