您的位置:首页 > 编程语言

在线编程--层次打印二叉树

2016-05-13 08:31 295 查看
题目信息:

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点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
TreeNode last=root;
TreeNode nlast=root;

LinkedList<TreeNode> queue=new LinkedList<TreeNode>();  //设置队列,层次遍历二叉树
List<List<Integer>> lists=new ArrayList<List<Integer>>();  //存储二叉树信息

queue.add(root);

List<Integer> list=new ArrayList<Integer>();

while(!queue.isEmpty()){

TreeNode node=queue.poll();
list.add(node.val);              //取出队列头的值存入数组中
if(node.left!=null){
queue.add(node.left);
nlast=node.left;            //nlast表示下一行的节点,nlast一直往后走,直到走到该行的最后一个
}
if(node.right!=null){
queue.add(node.right);
nlast=node.right;
}
if(node==last){                 //表示进行到最后一个,也就是说该行的节点遍历完毕,进行下一行
lists.add(list);
list=new ArrayList<Integer>();
last=nlast;
}
}

int n=lists.size();
int[][] res=new int
[];
for(int i=0;i<n;i++){
res[i]=new int[lists.get(i).size()];
for(int j=0;j<res[i].length;j++){
res[i][j]=lists.get(i).get(j);
}

}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: