【发布时间】:2014-10-31 04:25:37
【问题描述】:
假设我的树看起来像这样
5
/ \
1 8
/ \
6 9
我写了一个程序来找到这个的高度。
65 int height(const TNODE* root) {
66 if (root == NULL) {
67 return 0;
68 } else {
69 int lDepth = height(root->left);
70 int rDepth = height(root->right);
71 if (lDepth > rDepth) {
72 return (lDepth + 1);
73 } else {
74 return (rDepth + 1);
75 }
76
77 }
78 }
运行此方法会为上面的树打印 3。但是高度不应该是 2,因为这是从根到最远叶子的边数?我在网上搜索过,我得到了相互矛盾的信息。有人会说我上面的树的高度是 3,而其他人说是 2。
那么我上面的树应该是什么高度,为什么?
我的方法对吗?
【问题讨论】:
-
这显然取决于您的应用程序。根据您的应用选择符合您期望的。
-
到底是什么问题?
-
@igon 我已经添加了一些说明。
-
2 边高度和总是 2 + 1 节点高度。这取决于您计算节点还是边。
标签: c binary-tree