给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6] 输出:5
思路:首先这个题是要找从根节点到最近叶子结点的最短路径上的节点数量,即根节点到最近叶子结点的深度 如果root==null 直接返回0;root.left==null && root.right==null 返回1 然后一次去遍历左子树和右子树。在这里我刚开始是这样操作的 int left=minDepth(root.left)+1;int right=minDepth(root.right)+1;return left>right?right:left; 但是这样做是有 问题的
代码如下:
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);
//进行root左右子树是否为空的判断
if(root.left==null || root.right==null)
return left+right+1;
else
return left>right? right+1:left+1;
}
}