题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
知识点:
- 深度优先与广度优先遍历过程中层数的统计
解题思路:
- 这道题和59.按之字形顺序打印二叉树思路几乎是一摸一样,而且要简单,这道题我们不需要考虑打印顺序的问题直接按照广度优先遍历来便好,记得要统计层数
- 同样我们可以使用递归版来一次,不过递归版使用的深度优先遍历的理念,也就是说如果我们要统计遍历的层数,我们可以使用深度优先与广度优先都可
解题代码:
广度优先非递归版
// 广度优先非递归版function Print(pRoot){// write code hereif(!pRoot) return [];const res = [];const queue = [[pRoot,0]];while (queue.length) {let [temp,l] = queue.shift();if(!res[l]) {res[l] = [];res[l].push(temp.val);}else {res[l].push(temp.val);}if(temp.left) queue.push([temp.left,l+1]);if(temp.right) queue.push([temp.right,l+1]);}return res;}
深度优先递归版
// 深度优先递归版 function Print(pRoot) { // write code here if(!pRoot) return []; const res = []; const dfs = (node,deep) => { if(!res[deep]) { res[deep] = []; res[deep].push(node.val); }else { res[deep].push(node.val); } if(node.left) bfs(node.left,deep+1); if(node.right) bfs(node.right,deep+1); } bfs(pRoot,0); return res; }
