LeetCode【111. 二叉树的最小深度】

最小深度,看起来很简单,就是左右节点的深度最小值

定义一个函数,计算其深度

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null)
        {
            return 0;
        }
        else if(root.left == null && root.right ==null)
        {
            return 1;
        }
        else
        {
            int left = Depth(root.left);
            int right = Depth(root.right);
            if(left > right)
            {
            return left;
            }
            else
            {
                return right;
            }
        }
    }
    public int Depth(TreeNode root)
    {
        if(root == null)
        {
            return 0;
        }
        else
        {
            int left = Depth(root.left);
            int right = Depth(root.right);
            if(left<right)
            {
                return left+1;
            }
            else
            {
                return right+1;
            }
        }
    }
}

有错误在于,[1,2],只有一个节点,然后,该代码就会直接输出1,因为另一个没有节点,那么就直接是1

但实际上,应该是到叶子节点,不应该有叶子节点,而仍然只算根节点。

而且定义的函数其实和本函数类似,那么就可以直接迭代本函数,不需要另外定义。

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null)
        {
            return 0;
        }
        else if(root.left == null && root.right ==null)
        {
            return 1;
        }
        else
        {
            int left = minDepth(root.left);
            int right = minDepth(root.right);
            if(left == 0 && right > 0)
            {
                return right+1;
            }
            else if(right == 0 && left > 0)
            {
                return left+1;
            }
            else if(left > right)
            {
                return right+1;
            }
            else
            {
                return left+1;
            }
        }
    }
}

后面增加了上述情况,不会只算根节点。

原文地址:https://www.cnblogs.com/wzwi/p/10768417.html