題目:111. Minimum Depth of Binary Tree
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.
DFS的題绎秒。
注意必須是root-leaf的長(zhǎng),即如果root只有右子樹屡限,那么最小深度就是右子樹深度倦踢,不是0(左子樹深度)。所以比較左右深度斋陪,只在子樹不為0時(shí)才比較朽褪,否則就是INT最大VALUE。
第一次提交: min是global var无虚,
class Solution {
//必須是root-leaf的長(zhǎng)
int min;
public int minDepth(TreeNode root) {
if(root == null) return 0;
return Math.min(Integer.MAX_VALUE, countDepth(root, 0));
}
private int countDepth(TreeNode root, int count){
count++;
if(root.left == null && root.right == null){
return count;
}
int left = Integer.MAX_VALUE;
int right = Integer.MAX_VALUE;
if(root.left != null) left = countDepth(root.left, count);
if(root.right != null) right = countDepth(root.right, count);
min = Math.min(left, right);
return min;
}
}
寫完發(fā)現(xiàn)可以不需要int min缔赠。
class Solution {
//必須是root-leaf的長(zhǎng)
public int minDepth(TreeNode root) {
if(root == null) return 0;
return Math.min(Integer.MAX_VALUE, countDepth(root, 0));
}
private int countDepth(TreeNode root, int count){
count++;
if(root.left == null && root.right == null){
return count;
}
int left = Integer.MAX_VALUE;
int right = Integer.MAX_VALUE;
if(root.left != null) left = countDepth(root.left, count);
if(root.right != null) right = countDepth(root.right, count);
return Math.min(left, right);
}
}