从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
样例如下 思路:BFS 队列加载每个点
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[8, 12, 2, 6, 4]
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var printFromTopToBottom = function(root){
const res = []
if(!root) return res
const q = [root]
while(q.length) {
const node = q.shift()
res.push(node.val)
node.left && q.push(node.left)
node.right && q.push(node.right)
}
return res
}