LeetCode 111. 二叉树的最小深度 java题解

https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
注意,跟二叉树的最大深度求解完全不同。
// 当一个左子树为空,右不为空,这时并不是最低点
//因为叶子结点需要左右孩子都为空,当前节点有右孩子,不符合叶子结点。
//同理,当一个右子树为空,左不为空,这时并不是最低点。
//节点左右都不为空,节点左右都为空
int result = 1 + min(leftDepth, rightDepth);

class Solution {
    public int minDepth(TreeNode root){
        if(root==null) return 0;
        int left=minDepth(root.left);//左边最小深度
        int right=minDepth(root.right);//右边最小深度
        if(root.left==null&&root.right!=null){
            return right+1;
        }
        else if(root.left!=null&&root.right==null){
            return left+1;
        }
        //都为空,直接是1
        //都不为空
        //如果根节点的左右子树都不为空,分别递归计算左右子树的最小深度,取较小值加 1。
        else{
            return 1+Math.min(left,right);
        }
        //minDepth(root.left),minDepth(root.right)
    }
}

你可能感兴趣的:(LeetCode,leetcode,java,算法)