按层遍历打印二叉树(分层) -- 漫漫算法路 刷题篇
2017-09-07 17:33
316 查看
有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }*/ public class TreePrinter { public int[][] printTree(TreeNode root) { // write code here ArrayList<ArrayList<Integer>> alllist = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> list = new ArrayList<Integer>(); LinkedList<TreeNode> que = new LinkedList<TreeNode>(); if(root == null){ return null; } TreeNode last = root; TreeNode nlast = last; TreeNode node = null; que.add(root); while(!que.isEmpty()){ node = que.poll(); list.add(node.val); if(node.left!=null){ que.add(node.left); nlast=node.left; } if(node.right!=null){ que.add(node.right); nlast=node.right; } if(node==last){ alllist.add(list); last=nlast; list=new ArrayList<Integer>(); } } int[][] res = new int[alllist.size()][]; for(int i=0;i<alllist.size();i++){ res[i] = new int[alllist.get(i).size()]; for(int j=0;j<alllist.get(i).size();j++) res[i][j] = alllist.get(i).get(j); } return res; } }
相关文章推荐
- 按层遍历二叉树(不分层) -- 漫漫算法路 刷题篇
- 二叉树后序遍历数组 -- 漫漫算法路 刷题篇
- 算法题18 二叉树的前序、中序、后序、分层遍历
- 【二叉树】分层遍历二叉树和打印二叉树第k层节点
- 重建二叉树 -- 漫漫算法路 刷题篇
- 【LeetCode-面试算法经典-Java实现】【103-Binary Tree Zigzag Level Order Traversal(二叉树分层Z字形遍历)】
- 二叉树的层次遍历,从上到下和从下到上分层打印
- 二叉树的层次遍历及之形打印算法 Java实现
- 二叉树按层遍历打印的算法(c/c++)
- 二维数组中的查找、空格替换、从尾到头打印链表 --漫漫算法路 刷题篇
- 九章算法面试题7 分层遍历二叉树
- 【剑指offer】题60:分层遍历打印二叉树
- 【算法题】分层遍历二叉树
- 二叉树的建立和基础操作<三> —— (三种遍历及分层打印)
- java算法(一)二叉树逐层遍历打印(分层换行)
- 二叉树中和为某一值的路径 -- 漫漫算法路 刷题篇
- 从上往下打印二叉树(分层遍历)
- 【算法与数据结构】二叉树的 后序 遍历
- 按层打印二叉树的节点【层次遍历变形】
- 19、从上到下打印二叉树(层次遍历)