[二叉树]111. Minimum Depth of Binar
2017-11-01 本文已影响0人
Reflection_
题目: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的长,即如果root只有右子树,那么最小深度就是右子树深度,不是0(左子树深度)。所以比较左右深度,只在子树不为0时才比较,否则就是INT最大VALUE。
第一次提交: min是global var,
class Solution {
//必须是root-leaf的长
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;
}
}
写完发现可以不需要int min。
class Solution {
//必须是root-leaf的长
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);
}
}