Skip to content

Commit 07445d1

Browse files
committed
LC #102
1 parent b20b497 commit 07445d1

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

26-LeetCode/07-Binary-Tree-Level-Order-Traversal-LC-102.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,53 @@ return its level order traversal as:
1919
[15,7]
2020
]
2121
*/
22+
23+
/**
24+
* Definition for a binary tree node.
25+
* function TreeNode(val) {
26+
* this.val = val;
27+
* this.left = this.right = null;
28+
* }
29+
*/
30+
/**
31+
* @param {TreeNode} root
32+
* @return {number[][]}
33+
*/
34+
var levelOrder = function (root) {
35+
var result = [];
36+
37+
if (root === null) {
38+
return result;
39+
}
40+
41+
var queue = [];
42+
var temp = [];
43+
var curLvlCnt = 1;
44+
var nextLvlCnt = 0;
45+
46+
queue.push(root);
47+
48+
while (queue.length !== 0) {
49+
var p = queue.shift();
50+
temp.push(p.val);
51+
curLvlCnt--;
52+
53+
if (p.left) {
54+
queue.push(p.left);
55+
nextLvlCnt++;
56+
}
57+
if (p.right) {
58+
queue.push(p.right);
59+
nextLvlCnt++;
60+
}
61+
62+
if (curLvlCnt === 0) {
63+
result.push(temp);
64+
curLvlCnt = nextLvlCnt;
65+
nextLvlCnt = 0;
66+
temp = [];
67+
}
68+
}
69+
70+
return result;
71+
};

0 commit comments

Comments
 (0)