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.
一开始的考虑很有问题,忘了考虑是到结点(左右子树都为空)的路径,所以就有了下面的代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}
很显然,以上代码如果跑
2
1
得到的结果是1;
但是实际上应该是为2.。
修正后代码如下:添加了左子树为空,和 右子树为空的情况。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
if(root.left==null) return minDepth(root.right)+1;
if(root.right ==null) return minDepth(root.left)+1;
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}