每日三题//从上到下打印二叉树的不同玩法
1.从上到下打印二叉树(从左到右打印)
var levelOrder = function(root) {
if(!root) return []
const data=[]
const queue =[root]
while(queue.length){
const first = queue.shift();
data.push(first.val)
first.left && queue.push(first.left)
first.right && queue.push(first.right)
}
return data
};
2.从上到下打印(每层分别打印)
var levelOrder = function(root) {
if (!root) return [];
const queue = [root];
const res = []; // 存放遍历结果
let level = 0; // 代表当前层数
while (queue.length) {
res[level] = []; // 第level层的遍历结果
let levelNum = queue.length; // 第level层的节点数量
while (levelNum--) {
const front = queue.shift();
res[level].push(front.val);
if (front.left) queue.push(front.left);
if (front.right) queue.push(front.right);
}
level++;
}
return res;
};
3.从上到下打印(每层打印,但是奇数偶数显示反转)
var levelOrder = function(root) {
if(!root) return []
const queue =[root]
const res =[]
let level =0
while(queue.length){
res[level]=[]
let levelNum = queue.length;
while(levelNum--){
const front = queue.shift()
res[level].push(front.val)
front.left && queue.push(front.left)
front.right && queue.push(front.right)
}
if (level % 2) {
res[level].reverse();// 反转
}
level ++
}
return res
};
总结:队列+层序遍历:队列存储节点,但是js没有专门的队列,用数组来实现,入队:push;出队:shift