【发布时间】:2019-09-02 12:22:14
【问题描述】:
我有一个作业问题,要求编写一个递归填充二叉搜索树高度的方法。
下面是我的代码
我检查了这个问题的答案,这是有道理的,但我想知道我的方法是否是另一种有效的方法。
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++;
}
【问题讨论】:
-
如果它通过了所有的测试用例然后是。一个解决方案可以以“N”种方式实现。我们寻找的答案是时间和空间复杂度
标签: java recursion binary-search-tree