题解 | #把二叉树打印成多行#
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型二维数组 */ function Print(pRoot) { if (!pRoot) return []; let queue = []; let res = []; queue.push(pRoot); while (queue.length) { // 记录当前层次节点个数,因为弹出节点的同时会将其左右孩子节点加入队列,所以queue.length是变化的 // 因此必须要单独记录才能确定该层次弹出几个节点 let length = queue.length; let arr = []; for (let i = 0; i < length; i++) { let node = queue.shift(); arr.push(node.val); // 弹出节点的同时将其左右孩子节点加入到队列中 if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } res.push(arr); } return res; } module.exports = { Print: Print, };