原题链接在这里:https://leetcode.com/problems/minimum-depth-of-binary-tree/
本题与Maximum Depth of Binary Tree相似,不同是需要判断叶子节点,若是给出[1,2]这种情况,返回值应该是2而不是1,root的右节点为空,而根据定义:The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 此时root左节点不为空,所以root不能被认为是leaf.
AC Java:
/**
* 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;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if(root.left == null){
return right + 1;
}
if(root.right == null){
return left + 1;
}
return Math.min(left,right)+1;
}
}