-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevelOrderTraversal.js
More file actions
41 lines (36 loc) · 1.04 KB
/
Copy pathLevelOrderTraversal.js
File metadata and controls
41 lines (36 loc) · 1.04 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
/**
* 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)
* }
*/
var levelOrder = function (root) {
//Iterative approach
if (!root) return [];
let que = [root],
res = [];
while (que.length > 0) {
let temp = [];
let level = que.length;
for (let i = 0; i < level; i++) {
let curr = que.shift();
temp.push(curr.val);
curr.left && que.push(curr.left);
curr.right && que.push(curr.right);
}
res.push(temp);
}
return res;
// recursive
// if(!root) return [];
// const res = [];
// const finder = (curr, level) => {
// (res[level]) ? res[level].push(curr.val): res.push([curr.val]);
// curr.left && finder(curr.left, level + 1);
// curr.right && finder(curr.right, level + 1);
// }
// finder(root, 0);
// return res;
};