关于二叉树的按层打印
2016-09-04 21:58
183 查看
本文的思路来自于牛客网左程云大大的二叉树视频
视频地址
http://www.nowcoder.com/courses/1/1/1
题目要求如下:
至于算法分析,大家看视频吧,左老大讲的肯定比我清楚,下面是我实现的代码
视频地址
http://www.nowcoder.com/courses/1/1/1
题目要求如下:
至于算法分析,大家看视频吧,左老大讲的肯定比我清楚,下面是我实现的代码
class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Solution { public static void main(String[] args) { TreeNode t1=new TreeNode(1); TreeNode t2=new TreeNode(2); TreeNode t3=new TreeNode(3); TreeNode t4=new TreeNode(4); TreeNode t5=new TreeNode(5); TreeNode t6=new TreeNode(6); TreeNode t7=new TreeNode(7); TreeNode t8=new TreeNode(8); t1.left=t2; t1.right=t3; t2.left=t4; t3.left=t5; t3.right=t6; t5.left=t7; t5.right=t8; new Solution().printFromTopToBottom(t1); } public ArrayList<Integer> printFromTopToBottom(TreeNode root) { ArrayList<Integer> list=new ArrayList<Integer>(); Queue <TreeNode> queue=new ArrayBlockingQueue<>(100); TreeNode last=root; //当前行的最后节点 TreeNode nLast=root; //下一行的最右节点 queue.add(root); while (!queue.isEmpty()) { TreeNode out=queue.poll(); System.out.print(out.val+" "); list.add(out.val); if (out.left!=null) { queue.add(out.left); nLast=out.left; } if (out.right!=null) { queue.add(out.right); nLast=out.right; } if (out==last) { System.out.println(""); last=nLast; } } return list; } }
相关文章推荐
- 关于二叉树的若干代码, 非递归遍历,打印..
- 关于二叉树的按层打印
- 关于报表打印的几点技巧
- 关于jsp实现打印
- 关于打印系列之三
- 关于打印系列之一
- 一些关于分页打印的资料
- 抄来的关于CSS控制打印Table
- 关于web打印的总结!
- 关于WEB打印
- 关于MO打印时不能正确打印用DC自己画出来的图片的问题的解决方案
- 用分冶策略解决关于二叉树的几个问题
- [转] 关于ASP.NET页面打印技术的总结
- 关于打印机延迟打印任务的解决办法
- 关于WEB应用程序的打印组件开发初探
- 从二叉树和iterator看代码结构设计 (关于adapter的运用)
- 关于WEB应用程序的打印组件开发初探
- 关于System.Drawing.Print名称空间中给类对打印的管理与实现
- 关于二叉树前序输入且输出结构的算法实现
- 关于datagrid的打印