-
Notifications
You must be signed in to change notification settings - Fork 71
/
No111.minimum-depth-of-binary-tree.js
77 lines (72 loc) · 1.42 KB
/
No111.minimum-depth-of-binary-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Difficulty:
* Easy
*
* Desc:
* 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.
*
* 求树的最短路径上的节点数
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*
* 递归法
*/
var minDepth_1 = function(root) {
if (!root) return 0;
if (!root.left && !root.right) return 1;
const depth = [];
if (root.left) {
depth.push(
minDepth_1(root.left)
);
}
if (root.right) {
depth.push(
minDepth_1(root.right)
);
}
return 1 + Math.min(...depth);
};
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
* 迭代法
*/
var minDepth_2 = function(root) {
if (!root) return 0
let depth = Infinity
root.depth = 1
const queue = [root]
while (queue.length) {
const node = queue.pop()
if (!node.left && !node.right) {
depth = Math.min(depth, node.depth)
}
if (node.right) {
node.right.depth = node.depth + 1
queue.push(node.right)
}
if (node.left) {
node.left.depth = node.depth + 1
queue.push(node.left)
}
}
return depth
}