【问题标题】:Recursively filling the height of a Binary Search Tree?递归填充二叉搜索树的高度?
【发布时间】: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


【解决方案1】:

该解决方案的重要性在于它首先递归调用具有fillHeights(root.left);fillHeights(root.right);的根左右子树,然后仅之后比较结果。

你也错过了实际增加节点高度的重要部分,root.height++;

【讨论】:

  • 我忘记在答案的最后 2 个 if 语句末尾添加 +1。
猜你喜欢
  • 2015-04-08
  • 2018-05-06
  • 2014-01-02
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2019-04-17
  • 1970-01-01
相关资源
最近更新 更多