Question
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.
Solution 1 -- Recursion
Problems related with tree can always be solved by recursion. We need only consider three situations:
1. parent node
2. left child node
3. right chile node
Time complexity O(n), space cost O(1).
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public 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;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
Solution 2 -- Iteration
We can also solve this problem by visiting the tree level by level. Time complexity O(n), space cost O(n).
Notice that using ArrayList will save almost half time compared with using ArrayDeque. Actually, we need not to pop staff here.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
List<TreeNode> current = new ArrayList<TreeNode>();
List<TreeNode> next;
current.add(root);
int result = 1;
while (current.size() > 0) {
next = new ArrayList<TreeNode>();
int length = current.size();
for (TreeNode tmpNode : current) {
// If tmpNode is leaf node
if (tmpNode.left == null && tmpNode.right == null)
return result;
if (tmpNode.left != null)
next.add(tmpNode.left);
if (tmpNode.right != null)
next.add(tmpNode.right);
}
current = next;
result++;
}
return result;
}
}
Discussion
Recursion is not always the time consuming solution. For example, in this problem, every node has been calculated height for only once, so there's no redundance. However, for Fibonacci problem, when we calculate F(5), we get F(5) = F(4) + F(3), which is redundant calculation. Under this circumtance, we should use Dynamic Programming.