第31题 – 从上往下打印二叉树(层序遍历)
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
即求二叉树的层序遍历。
1. 建立一个队列qu。
2. 先把root指针放入qu。
3. ♻️循环队列。出队一个节点,将非空的左右子节点入队。把当前节点的数值存入结果数组。
4. 返回结果数组。
JavaScript实现
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root)
{
if(root === null) return [];
let qu = [root], p = root, rel = [];
while(qu.length > 0){
p = qu.shift();
rel.push(p.val);
if(p.left !== null) qu.push(p.left);
if(p.right !== null) qu.push(p.right);
}
return rel;
}