我有一个作业问题,要求写一个递归填充二叉搜索树高度的方法。
下面是我的代码
我检查了这个问题的答案键,这很有意义,但是我想知道我的方法是否是解决此问题的另一种有效方法。
public static <T extends Comparable> void fillsHeight(BSTNode root){
if (root == null) return;
if (root.left == null && root.right == null) root.height = 0;
if (root.left != null) height = root.left.height + 1;
if (root.right != null) height = Math.max(height, root.right.height) + 1;
fillsHeight(root.left);
fillsHeight(root.right);
}
以下是答案键的官方解决方案:
public static <T extends Comparable>
void fillHeights(BSTNode root) {
if (root == null) { return; }
fillHeights(root.left);
fillHeights(root.right);
root.height = -1;
if (root.left != null) {
root.height = root.left.height;
}
if (root.right != null) {
root.height = Math.max(root.height, root.right.height);
}
root.height++;
}
答案 0 :(得分:0)
该解决方案的重要性在于,它首先使用fillHeights(root.left);
和fillHeights(root.right);
递归地调用根左边和右边的子树,然后之后比较结果。< / p>
您还缺少使用root.height++;