111. Minimum Depth of Binary Tree(二叉树)

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.


思路一样,代码是作者caiqi8877的比较简洁

public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
       
    }
}

我的代码

public int minDepth(TreeNode root) {
                if(root==null)
return 0;
if(root.left==null&&root.right==null)
return 1;
if(root.left==null)
return minDepth(root.right)+1;
if(root.right==null)
return minDepth(root.left)+1;
else
return Math.min(minDepth(root.left), minDepth(root.right))+1;
    }

最近刷题太浮躁,看到二叉树的题就递归,结果不停犯错。。

扫描二维码关注公众号,回复: 762418 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_39525565/article/details/80240876
今日推荐