题解 | #把二叉树打印成多行#
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
/*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 [] const res: number[][] = [] const queue: TreeNode[][] = [[pRoot]] while (queue.length > 0) { const currentLayerNodes = queue.shift() res.push(currentLayerNodes.map(({ val }) => val)) const nextLayerNodes = [] for (let i = 0; i < currentLayerNodes.length; i++) { if (currentLayerNodes[i].left) { nextLayerNodes.push(currentLayerNodes[i].left) } if (currentLayerNodes[i].right) { nextLayerNodes.push(currentLayerNodes[i].right) } } if (nextLayerNodes.length > 0) { queue.push(nextLayerNodes) } } return res }