从上到下打印二叉树
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
1
2
3
4
5
6
7
2
3
4
5
6
7
返回:
[3,9,20,15,7]
1
/**
* 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) {
if(root === null) return []
let queue = []
let ans = []
queue.push(root)
while(queue.length) {
let curr = queue.shift()
ans.push(curr.val)
if(curr.left) {
queue.push(curr.left)
}
if(curr.right) {
queue.push(curr.right)
}
}
return ans
};
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
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
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
← 最小K个数 第一个只出现一次的字符→