-
Notifications
You must be signed in to change notification settings - Fork 0
/
102.binary-tree-level-order-traversal.js
84 lines (75 loc) · 1.49 KB
/
102.binary-tree-level-order-traversal.js
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
80
81
82
83
84
/*
* @lc app=leetcode id=102 lang=javascript
*
* [102] Binary Tree Level Order Traversal
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function helper(list, ret) {
if (list.length === 0) return;
let nextArr = [];
let nextVal = [];
for (let i = 0; i < list.length; i++) {
let temp = list[i];
if (temp.left) {
nextArr.push(temp.left);
nextVal.push(temp.left.val);
}
if (temp.right) {
nextArr.push(temp.right);
nextVal.push(temp.right.val);
}
}
if (nextVal.length !== 0) {
ret.push(nextVal);
}
helper(nextArr, ret);
}
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
let ret = [];
if (!root) return ret;
ret.push([root.val]);
helper([root], ret);
return ret;
};
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
let ret = [];
let queue = [root];
if (!root) return ret;
while (queue.length !== 0) {
let len = queue.length;
let sub = [];
for (let i = 0; i < len; i++) {
let temp = queue.shift();
sub.push(temp.val);
if (temp.left) {
queue.push(temp.left);
}
if (temp.right) {
queue.push(temp.right);
}
}
ret.push(sub);
}
return ret;
};