题目
-
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
-
例如:给定二叉树: [3,9,20,null,null,15,7],返回:[3,9,20,15,7]
3
/ \
9 20
/ \
15 7 -
leetcode链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/solution/
思路
- 利用队列实现node先进先出
代码
/**
* 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) return []
const queue = [root]
const res = []
while (queue.length) {
const node = queue.shift()
res.push(node.val)
if (node.left) queue.push(node.left)
if (node.right) queue.push(node.right)
}
return res
};