Skip to content

Commit f5b7405

Browse files
committed
feat: Binary Tree Level Order Traversal
1 parent 100154c commit f5b7405

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// n: number of nodes
2+
// Time complexity: O(n)
3+
// Space complexity: O(n)
4+
5+
class _Queue {
6+
constructor() {
7+
this.q = [];
8+
this.front = 0;
9+
this.rear = 0;
10+
}
11+
12+
push(value) {
13+
this.q.push(value);
14+
this.rear++;
15+
}
16+
17+
shift() {
18+
const rv = this.q[this.front];
19+
delete this.q[this.front++];
20+
return rv;
21+
}
22+
23+
isEmpty() {
24+
return this.front === this.rear;
25+
}
26+
}
27+
28+
/**
29+
* Definition for a binary tree node.
30+
* function TreeNode(val, left, right) {
31+
* this.val = (val===undefined ? 0 : val)
32+
* this.left = (left===undefined ? null : left)
33+
* this.right = (right===undefined ? null : right)
34+
* }
35+
*/
36+
/**
37+
* @param {TreeNode} root
38+
* @return {number[][]}
39+
*/
40+
var levelOrder = function (root) {
41+
const answer = [];
42+
const q = new _Queue();
43+
44+
if (root) {
45+
q.push([root, 0]);
46+
}
47+
48+
while (!q.isEmpty()) {
49+
const [current, lv] = q.shift();
50+
51+
if (answer.at(lv) === undefined) {
52+
answer[lv] = [];
53+
}
54+
55+
answer[lv].push(current.val);
56+
57+
if (current.left) {
58+
q.push([current.left, lv + 1]);
59+
}
60+
61+
if (current.right) {
62+
q.push([current.right, lv + 1]);
63+
}
64+
}
65+
66+
return answer;
67+
};

0 commit comments

Comments
 (0)