Aug 3 2017 Update
递归方法1:
private 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;
int min = Math.min(minDepth(root.left), minDepth(root.right));
return min + 1;
}
树只有一个孩子的情况要去递归执行它的孩子,depth要+1。
最后那个int min也要+1, 因为还要把根结点算上。
递归方法2:
感觉比1难懂一点。。其实一样。
public int minDepth(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;
}
--
原来的post
递归方法通用只需要3行。
非递归方法:
public int minDepth(TreeNode root) {
if (root == null) return 0;
int level = 0;
int curNum = 1;
int nextNum = 0;
LinkedList<TreeNode> linkedList = new LinkedList<>();
linkedList.add(root);
while (!linkedList.isEmpty()) {
TreeNode node = linkedList.poll();
curNum--;
if (node.left == null && node.right == null)
return level + 1;
if (node.left != null) {
linkedList.add(node.left);
nextNum++;
}
if (node.right != null) {
linkedList.add(node.right);
nextNum++;
}
if (curNum == 0) {
curNum = nextNum;
nextNum = 0;
level++;
}
}
return level;
}