-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy path从上到下打印二叉树.js
More file actions
33 lines (33 loc) · 751 Bytes
/
从上到下打印二叉树.js
File metadata and controls
33 lines (33 loc) · 751 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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
剑指 Offer 32 - I. 从上到下打印二叉树
*/
var levelOrder = function(root) {
const queue = [root];
const ans = [];
while (queue.length) {
let size = queue.length;
while (size > 0) {
let top = queue.shift();
if (top) {
ans.push(top.val);
}
if (top && top.left) {
queue.push(top.left);
}
if (top && top.right) {
queue.push(top.right);
}
size--;
}
}
return ans;
};