题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param pRoot TreeNode类 * @return int整型二维数组 */ export function Print(pRoot: TreeNode): number[][] { // write code here if (pRoot === null) return [] let l2r = true const result = [] const cache: TreeNode[][] = [[pRoot]] while (cache.length > 0) { const headCache = cache.shift() const headCopy = [...headCache] if (!l2r) { headCache.reverse() l2r = true } else { l2r = false } result.push(headCache.map(({ val }) => val)) const current = [] for (let i = 0; i < headCopy.length; i++) { if (headCopy[i].left) { current.push(headCopy[i].left) } if (headCopy[i].right) { current.push(headCopy[i].right) } } if (current.length > 0) { cache.push(current) } } return result }