Problem
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]
,
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
Solution 1
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (!root) return 0;
if (!root.left) return minDepth(root.right) + 1;
if (!root.right) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
};
Explain:
dfs
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).
Solution 2
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (!root) return 0;
var queue = [[root, 1]];
var item = null;
var node = null;
var level = 0;
while (queue.length) {
item = queue.shift();
node = item[0];
level = item[1];
if (!node.left && !node.right) return level;
if (node.left) queue.push([node.left, level + 1]);
if (node.right) queue.push([node.right, level + 1]);
}
};
Explain:
bfs
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).