题目描述:
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.
中文理解:获取二叉树的的最小深度。
解题思路:不能单纯使用递归来解题,因为对于极限情况一棵树最不平衡的情况,那样得到的结果是1,和最终的预期不同,故需要考虑根节点的一个子树为空的情况。
代码(java):
/**
* 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;
int leftMinDepth=minDepth(root.left);
int rightMinDepth=minDepth(root.right);
if(leftMinDepth==0|| rightMinDepth==0){
return 1+Math.max(leftMinDepth,rightMinDepth);
}
else{
return 1+Math.min(leftMinDepth,rightMinDepth);
}
}
}