题解 | #按之字形顺序打印二叉树-与层序遍历一致#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
记录层次--改变收集答案时的代码
function Print(pRoot)
{
// write code here
let res = []
if(!pRoot) return res;
let q = [[pRoot,0]];
while(q.length){
const [n,l] = q.shift();
if(!res[l]){
res.push([n.val]);
}else{
if(l % 2 === 0 ){
res[l].push(n.val);
}else{
res[l].unshift(n.val);
}
}
if(n.left) q.push([n.left,l+1]);
if(n.right) q.push([n.right,l+1]);
}
return res;
}
一层一层的访问,有条件的改变答案的插入
(这里不是改变队列中节点的插入,而是答案收集时的插入)
function Print(pRoot)
{
// write code here
let res = []
if(!pRoot) return res;
let q = [pRoot];
let l = 0;
while(q.length){
let len = q.length;
res.push([]);
l++;
while(len--){
const n = q.shift();
//答案收集时的有条件地更改
if(l % 2 == 0){
res[res.length - 1].unshift(n.val);
}else{
res[res.length - 1].push(n.val);
}
if(n.left) q.push(n.left);
if(n.right) q.push(n.right);
}
}
return res;
}