求二叉树的最小深度,与求二叉树的最大深度相比,当遇到一个结点的左(右)结点为空时,这个结点并不属于叶子节点,可以考虑返回子节点的最大值。
/**
* 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) {
return minDepths(root);
}
private int minDepths(TreeNode node){
if(node == null) return 0;
int leftD = minDepths(node.left);
int rightD = minDepths(node.right);
if(leftD != 0 && rightD != 0) return Math.min(leftD, rightD) + 1;
else return Math.max(leftD, rightD) + 1;
}
}
via: http://pmvt.cn/develop/leetcode-maximum-depth-minimum-depth-of-a-binary-tree.html http://www.cnblogs.com/felixfang/p/3887565.html