Description
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
return its minimum depth = 2.
Solution
DFS, time O(n), space O(h)
題目有坑啊漂辐,一定注意驶臊,是從root到left的minDepth!而非root到null的澳盐!如果root.right == null东揣,minDepth不是1循衰,而是應(yīng)該計算root到leftTree的leaf才對厢漩。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null) {
return 1 + minDepth(root.right);
} else if (root.right == null) {
return 1 + minDepth(root.left);
} else {
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
}
BFS, time O(n), space O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 1;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
TreeNode curr = queue.poll();
if (curr.left == null && curr.right == null) {
return depth;
}
if (curr.left != null) {
queue.offer(curr.left);
}
if (curr.right != null) {
queue.offer(curr.right);
}
}
++depth;
}
return -1;
}
}