forked from lazzzis/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
79 lines (72 loc) · 1.41 KB
/
Copy pathmain.js
File metadata and controls
79 lines (72 loc) · 1.41 KB
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
/**
* 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 == null) return 0
const q = new Queue()
q.push({ root, depth: 1 })
while (!q.empty()) {
const top = q.pop()
const root = top.root
if (root.left == null && root.right == null) return top.depth
if (root.left) {
q.push({
root: root.left,
depth: top.depth + 1
})
}
if (root.right) {
q.push({
root: root.right,
depth: top.depth + 1
})
}
}
return 0
}
class Queue {
constructor () {
this._front = this._back = { val: null, next: null }
this._length = 0
}
push (val) {
this._back.next = {
val,
next: null
}
this._back = this._back.next
this._length += 1
}
pop () {
if (this._length === 0) {
throw new Error('failed to pop: empty queue')
}
this._length -= 1
this._front = this._front.next
return this._front.val
}
top () {
if (this._length === 0) {
throw new Error('Failed to top: empty queue')
}
return this._front.next.val
}
get length () {
return this._length
}
empty () {
return this._length === 0
}
clear () {
this._front = this._back = { val: null, next: null }
this._length = 0
}
}