把二叉树打印成多行 Posted on 2019-08-13 | | reads times 把二叉树打印成多行题目描述 从上层到下层从左到右按层输出二叉树 用队列先进先出的性质,从左到右先遍历下层节点,到下层输出的时候,也可以从左到右输出。 需要记录下层节点的个数 需要记录当前层打印节点的个数 123456789101112131415161718192021222324252627282930313233function Print(pRoot){ // write code here const queue=[] const res=[] if(pRoot==null){ return res; } let nextlevel=0; let curlevel=1; queue.push(pRoot); let list=[] while(queue.length!=0){ const pNode=queue.shift(); list.push(pNode.val) if(pNode.left!=null){ nextlevel++; queue.push(pNode.left) } if(pNode.right!=null){ nextlevel++; queue.push(pNode.right) } curlevel--; if(curlevel==0){ res.push(list) curlevel=nextlevel; nextlevel=0; list=[]; } } return res;} Post author: GoldMiner Xun Post link: https://goldminerxun.github.io/2019/08/13/%E5%89%91%E6%8C%87offer%20JavaScript%E7%89%88%20(60)/ Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.