描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}
该二叉树之字形层序遍历的结果是
[
[1],
[3,2],
[4,5]
]
js代码
这题就和层序遍历一样的,多了一个深度的判断而已
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Print(pRoot)
{
// write code here
let ans=[]
function dfs(root,h){
if(!root) return
if(!ans[h]) ans[h]=[]
if(h%2==0){
ans[h].push(root.val)
}else{
ans[h].unshift(root.val)
}
dfs(root.left,h+1)
dfs(root.right,h+1)
}
dfs(pRoot,0)
return ans
}
module.exports = {
Print : Print
};