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.
題意:求一棵二叉樹(shù)的最小高度(深度)。
思路:
104題是求最大高度,本題是求最小高度,解法是大致相同的。
用分治的方法求非葉子節(jié)點(diǎn)左右子樹(shù)的最小高度。
考慮到[1,null,2]這種二叉樹(shù),左子樹(shù)是空,如果空樹(shù)返回的高度是0,求左右子樹(shù)最小高度的時(shí)候,0比1小,會(huì)有bug。所以遞歸求解的時(shí)候,先判斷左右節(jié)點(diǎn)是否是null。
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return helper(root);
}
public int helper(TreeNode root) {
int min = Integer.MAX_VALUE;
if (root.left != null) {
int left = helper(root.left);
min = Math.min(min, left);
}
if (root.right != null) {
int right = helper(root.right);
min = Math.min(min, right);
}
return min == Integer.MAX_VALUE ? 1 : 1 + min;
}
翻看discuss,排名最高的解法對(duì)null節(jié)點(diǎn)直接返回0,通過(guò)一個(gè)left == 0 || right == 0的判斷,即可知道要如何返回的最小高度,解法非常簡(jiǎn)練!
public int minDepth1(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
}