题目链接:
- 牛客网:从上往下打印二叉树
题解:
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root)
{
// write code here
if (!root) return []
// 创建一个队列用于层序遍历
const rootQueue = []
// 创建结果数组
const res = []
// 一开始的时候,将头节点加入队列中
rootQueue.push(root)
// 如果队列中有结点,则继续循环
while (rootQueue.length) {
// 获取队列头部的结点
const top = rootQueue[0]
// 推入结果数组中
res.push(top.val)
// 如果该结点有左子树
if (top.left) {
// 将左子树加入到队列中
rootQueue.push(top.left)
}
// 如果该结点有右子树
if (top.right) {
// 将右子树加入到队列中
rootQueue.push(top.right)
}
// 队列头部元素出队
rootQueue.shift()
}
// 返回结果数组
return res
}
总结:
二叉树的层序遍历,借助队列。初始时将头部结点推入队列中,如果队列中有元素,进入 while 循环,在循环中将左右子树加入队列,进入下次 while 循环,直至遍历所有结点,这样就对二叉树进行了完整一遍层序遍历。