给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
注意:它是到最近的叶子节点,要多考虑根节点
class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int leftH = minDepth(root.left);
int rightH = minDepth(root.right);
if(leftH == 0 || rightH == 0)
return leftH + rightH + 1;
else
return Math.min(leftH,rightH) + 1;
}
}
class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int leftH = 0;
if(root.left != null)
leftH = minDepth(root.left);
int rightH = 0;
if(root.right != null)
rightH = minDepth(root.right);
if(leftH == 0)
return rightH + 1;
else if(rightH == 0)
return leftH + 1;
else
return Math.min(leftH,rightH) + 1;
}
}
和按行打印二叉树一样,当当前节点cur和last节点相同的时候,说明要换行了!
class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int res = 1;
TreeNode nlast = null;
TreeNode last = root;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
nlast = root;
while(!queue.isEmpty()){
TreeNode cur = queue.poll();
if(cur.left == null && cur.right == null )
return res;
if(cur.left != null){
queue.offer(cur.left);
nlast = cur.left;
}
if(cur.right != null){
queue.offer(cur.right);
nlast = cur.right;
}
if(cur == last){
last = nlast;
res++;
}
}
return res;
}
}