题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
this.val = x;
this.left = null;
this.right = null;
} */
function Print(pRoot)
{
// write code here
let res=[]
let d=0
let d1=0
let arr=[]
if(pRoot!=null){
let res1=[]
res1.push(pRoot.val)
res.push(res1)
if(d==0){d=1;}
else if(d==1){d=0;}
arr.push(pRoot)
}
while(d1!=d){
let res1=[]
d1=d
let arr2=findnext(d,arr)//d=0从右x=向左打印
arr=arr2
if(arr2.length==0){return res}
else{
for(let i=0;i<arr2.length;i++){
res1.push(arr2[i].val)
}
if(d==0){d=1;}
else if(d==1){d=0;}
res.push(res1)
}
}
return res
}
function findnext(d,arr){
let res=[]
if(d==1){
for(let i=arr.length-1;i>=0;i--){
if(arr[i].right!=null){res.push(arr[i].right)}
if(arr[i].left!=null){res.push(arr[i].left)}
}
}
else{
for(let i=arr.length-1;i>=0;i--){
if(arr[i].left!=null){res.push(arr[i].left)}
if(arr[i].right!=null){res.push(arr[i].right)}
}
}
return res
}
module.exports = {
Print : Print
};
这道题终于过了。。每次输出下一次的节点数组(节点的信息量更大),val再循环取一遍就行