-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbinaryTreeLevelOrder.js
More file actions
40 lines (36 loc) · 845 Bytes
/
binaryTreeLevelOrder.js
File metadata and controls
40 lines (36 loc) · 845 Bytes
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
let result = [];
let stack = [];
if (root === null) {
return result;
}
stack.push([root, 0]);
let current;
let depth;
while (stack.length > 0) {
[current, depth] = stack.pop();
if (result[depth] === undefined) {
// result.push([]);
result[depth] = [];
}
result[depth].push(current.val);
if (current.right !== null) {
stack.push([current.right, depth + 1]);
}
if (current.left !== null) {
stack.push([current.left, depth + 1]);
}
}
return result;
};