题解 | #JZ77 按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
```/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Print(pRoot)
{
// write code here
if(pRoot === null ){return []}
let resArr=[]
let oddStack=[] //奇数层节点
let evenStack=[] //偶数层节点
let index=1
oddStack.push(pRoot) //第一层的根节点推入
while(oddStack.length||evenStack.length){
if(index%2===1){ //处理奇数层出栈,子节点入偶数层
let temp=[]
while(oddStack.length){
let node=oddStack.pop()
temp.push(node.val)
if(node.left){evenStack.push(node.left)} //每一个奇数层子节点(如果存在)按顺序推入evenstack
if(node.right){evenStack.push(node.right)}
}
resArr.push(temp)
index++
}
else{ //处理偶数层出栈,子节点入奇数层
let temp=[]
while(evenStack.length){
let node=evenStack.pop()
temp.push(node.val)
if(node.right){oddStack.push(node.right)} //每一个偶数层的子节点(如果存在)按顺序推入oddStack
if(node.left){oddStack.push(node.left)}
}
resArr.push(temp)
index++
}
}
return resArr
}
module.exports = {
Print : Print
};