题解 | #把二叉树打印成多行#
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
// 解题思路:bfs // 使用队列来存储节点值 // 注意特殊输入,比如空树的情况 /* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型二维数组 */ function Print(pRoot) { // write code here if(pRoot==null)return []; const queue = [pRoot]; const result = []; let subResult; while (queue.length) { // 记得要重置一下 console.log(queue.length); subResult = []; const len=queue.length; // 注意for中的len是会重新计算的,需要提前存下来,如果你写成queue.length的话,则是会影响遍历次数,导致错误 for (let i = 0; i < len; i++) { const root = queue.shift(); subResult.push(root.val); root.left && queue.push(root.left); root.right && queue.push(root.right); } console.log(subResult); result.push(subResult); } return result; } module.exports = { Print: Print, };