题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型二维数组 */ function Print( pRoot ) { // write code here //思路:先把每一行的节点放入数组里面,之后奇数的话就不反转,偶数的话就反转。 //当中间的交互节点的 let arr = [] //储存结果 let res = [] let layer = 1 //判断节点是否为空 if(!pRoot)return res //这个是来寻找节点的 arr.push(pRoot) while(arr.length){ //储存每一层的节点 let temp = [] let length = arr.length //负责找到每一层的节点 while(length){ let node = arr.shift() temp.push(node.val) if(node.left)arr.push(node.left) if(node.right)arr.push(node.right) length-- } //判断奇偶 //奇数直接加入 if(layer % 2){ res.push(temp) }else{ res.push(temp.reverse()) } layer++ } return res } module.exports = { Print : Print };