-
Notifications
You must be signed in to change notification settings - Fork 0
/
0111.MinimumDepthofBinaryTree.js
130 lines (92 loc) · 2.71 KB
/
0111.MinimumDepthofBinaryTree.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// 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 1:
// Input: root = [3,9,20,null,null,15,7]
// Output: 2
// Example 2:
// Input: root = [2,null,3,null,4,null,5,null,6]
// Output: 5
//
// Constraints:
// The number of nodes in the tree is in the range [0, 105].
// -1000 <= Node.val <= 1000
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree
// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
// 🎨 方法一:DFS
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
return dfs(root, 1, Infinity);
};
function dfs(root, deep, minDeep) {
if (root === null) {
return 0
}
if (root.left === null && root.right === null) {
minDeep = deep;
}
let minDeepLeft = Infinity
if (root.left) {
minDeepLeft = dfs(root.left, deep + 1, minDeep);
}
let minDeepRight = Infinity
if (root.right) {
minDeepRight = dfs(root.right, deep + 1, minDeep)
}
return Math.min(minDeep, minDeepLeft, minDeepRight)
}
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
// 🎨 方法二:BFS
// 📝 思路:用两个队列分别存储节点和节点的深度
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
if (root === null) {
return 0
}
const queNode = [root]
const queDeep = [1];
let minDeep = Infinity
while (queNode.length) {
let size = queNode.length;
while (size) {
let currNode = queNode.shift();
let currDeep = queDeep.shift();
if (currNode.left === null && currNode.right === null) {
minDeep = Math.min(minDeep, currDeep);
}
if (currNode.left) {
queNode.push(currNode.left)
queDeep.push(currDeep + 1);
}
if (currNode.right) {
queNode.push(currNode.right)
queDeep.push(currDeep + 1);
}
size--
}
}
return minDeep
};