/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
return depth(root);
}
public int depth(TreeNode root){
if(root.left==null&&root.right==null) return 1; //如果是叶子才返回
if(root.left==null) return depth(root.right)+1; //如果只有左边为null,说明肯定不是叶子,继续往右下一层
if(root.right==null) return depth(root.left)+1; //如果只有右边为空,说明肯定不是叶子,继续往左下一层
//如果左右都不为空,则看两遍最小的叶子
return Math.min(depth(root.left),depth(root.right))+1;
}
}
[leetcode]111. Minimum Depth of Binary Tree
猜你喜欢
转载自blog.csdn.net/weixin_36869329/article/details/89472058
今日推荐
周排行