题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
function Print(pRoot)
{
//最终输出的结果
let result = []
//记录当前层数
let depth = 0
//每一层的节点
let mid_result = []
//判空
if(!pRoot) return result
if(!pRoot.left&&!pRoot.right){
mid_result.push(pRoot.val)
result.push(mid_result)
return result
}
//保存当前层节点
let current = []
//保存下一层层节点
let next = []
current.push(pRoot)
while(current.length||next.length){
while(current.length){
// 添加一个节点的左右孩子后就将其弹出
if(current[0].left) next.push(current[0].left)
if(current[0].right) next.push(current[0].right)
mid_result.push(current[0].val)
current.shift()
}
// current为空,说明当前层遍历完
depth++
if(depth%2===0){
result.push(mid_result.reverse())
}
else{
result.push(mid_result)
}
mid_result = []
current = next
next = []
}
return result
}
module.exports = {
Print : Print
};