[英]Is it possible to write an algorithm that takes the binary tree T and returns an integer value that represents the height of T
所以我目前正在阅读 Java 第六版中的数据结构和算法,书中的一个练习说:
编写算法,采用二叉树 T 并返回一个表示 T 高度的整数值。回想一下,二叉树的高度是树的根与其最远叶子之间的边数。 例如,以下树的高度为 3:
树看起来像这样:
A
/ \
B C
/ \ \
D E F
\
G
现在,如果有人可以就我应该如何开始它提供一些指示,那将是非常棒的,因为目前我正在为这项练习而苦苦挣扎。
非常感谢你。
编辑:我道歉,我完全忘记了我的伪代码,这里是:
Algorithm Total_Height (L_subtree, R_subtree, root)
Total_Height (root) {
If (root == null)
Return – 1
Return max (Total_Height( root-> L_subtree), Total_Height (root-> R_subtree))
}
对此可以做出的任何评论或改进将不胜感激。
要获得树的“高度”,您必须跟踪您现在所处的深度:
int Tree_Height(root, depth) {
if (root == null) {
return -1;
}
return max(
Tree_Height(root.L_subtree, depth + 1),
Tree_Height(root.R_subtree, depth + 1),
depth
);
}
您需要max
函数中的深度,因为在树的末尾,结果将为 -1,它将传播到顶部,而该函数的整体结果将为 -1。
如果你不理解这个解释,试着在一张纸上跟踪你的程序的执行。 这在修复递归中的错误时总是有帮助的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.