剑指 Offer 32 - I. 从上到下打印二叉树
题目描述:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印
示例:
给定二叉树: [3,9,20,null,null,15,7],
输出:[3,9,20,15,7]
思路:
借助队列先进先出对二叉树进行遍历
代码:
var levelOrder = function(root) {
if (root === null) return []
let queue = []
queue.push(root)
let result = []
while(queue.length > 0) {
let node = queue.shift()
result.push(node.val)
if (node.left !== null) queue.push(node.left)
if (node.right !== null) queue.push(node.right)
}
return result
};