【问题标题】:Finding minimum depth of BST ... findHeight function won't work寻找 BST 的最小深度 ... findHeight 函数不起作用
【发布时间】:2021-05-27 11:24:27
【问题描述】:

尝试解决这个 LC Easy:https://leetcode.com/problems/minimum-depth-of-binary-tree/

这是找到一棵树的最小深度(最短路径上的节点数)。

我能够创建一个“findheight”函数,它可以给我一棵树的高度。

我的逻辑是使用 findheight 找到根节点的两个子树(左和右)的高度,然后返回两个高度之间的最小值。

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null){return 0;}
        int left = findHeight(root.left);
        int right = findHeight(root.right);

        //unbalanced tree, only one subtree 
        if(left == 0 || right == 0){
            return Math.max(left,right) + 1;
        }
        return Math.min(left,right) + 1 ;
    }
    
    public int findHeight(TreeNode root){
        if(root == null){return 0;}
        int left = findHeight(root.left);
        int right = findHeight(root.right);
        return Math.max(left,right) + 1;
    }
}

它不会通过测试用例:

[-9,-3,2,null,4,4,0,-6,null,-5]

或者:

Output:
4
Expected:
3

我现在的想法是,当我使用“findHeight”时,我将返回每个左右子树的“最大”高度。在这个测试用例中,我应该返回最小高度。

我在另一次迭代中将代码更改为“Math.min”,但这也不起作用。

任何想法或理论为什么?如此迷茫!!我应该完全放弃这种方法吗?

【问题讨论】:

  • 在帖子中直接描述您的代码、问题以及您想要实现的目标,而不是引用外部链接
  • 对不起,我是 StackOverflow 的新手。我已经编辑了我的问题以进一步解释我的思考过程。
  • @buddybuddybuddybuddy, findHeight 当前找到最大高度。我添加了一个有效的答案。

标签: java binary-search-tree depth-first-search breadth-first-search depth


【解决方案1】:

当前代码中的问题

//unbalanced tree, only one subtree 
if(left == 0 || right == 0){
  return Math.max(left,right) + 1;
}

上面的代码行只检查root level的不平衡。它不会递归检查较低级别的不平衡。

检查每个级别的不平衡

    public int minDepth(final TreeNode node) {
        if (node == null) {
            return 0;
        }
        final int left = minDepth(node.left);
        final int right = minDepth(node.right);
        
        // if both paths exist, then return the minimum
        if (node.left != null && node.right != null) {
            return Math.min(left, right) + 1;
        } else {
            // if zero or one path exists return that path (so take maximum)
            return Math.max(left, right) + 1;
        }
    }

【讨论】:

  • 感谢您提供良好注释的代码,我将探索和试验您的解决方案!
猜你喜欢
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
相关资源
最近更新 更多