-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102_binary_tree_level_order_traversal.ts
More file actions
47 lines (43 loc) · 1.25 KB
/
Copy path102_binary_tree_level_order_traversal.ts
File metadata and controls
47 lines (43 loc) · 1.25 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
/**
* Insantiate queue with root, then while queue is not empty: shift through
* old level, pushing children to queue and keep track of level size
* */
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function levelOrder(root: TreeNode | null): number[][] {
const result: number[][] = [];
if (!root) return [];
const q: TreeNode[] = [];
let levelSize = 1;
q.push(root);
while(q.length > 0) {
const level: number[] = [];
let newLevelSize = 0;
for (let i = 0; i < levelSize; i++) {
const node = q.shift();
level.push(node.val);
if (node.left){
q.push(node.left);
newLevelSize++;
}
if (node.right) {
q.push(node.right);
newLevelSize++;
}
}
result.push(level);
levelSize = newLevelSize;
}
return result;
};