leetCode111.二叉树的最小深度

典型的递归题,没啥值得好说的。需要注意的是必须要到跟节点,也就是只要左右子节点有一个不为空都要继续递归下去。递归停止时,返回值可能为0,因此不能直接使用Math.min,要把得0的情况从比较中去除。

public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        if(root.left == null && root.right == null){
                return 1;
        }else{
                return 1 + getMin(minDepth(root.left), minDepth(root.right));
        }
    }
    public int getMin(int a, int b){
        if (b == 0)
            return a;
        if (a == 0)
            return b;
        if (a >= b) 
            return b;
        if (a < b) 
            return a;
        return 0;
    }
image.png

你可能感兴趣的:(leetCode111.二叉树的最小深度)