有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点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;//表示当前行的最右结点
TreeNode nlast;//表示下一行的最右结点
//用一个队列来装要打印的结点
LinkedList<TreeNode> link = new LinkedList<TreeNode>();
//用数组来装打印之后的结点
ArrayList<ArrayList<Integer>> layer=new ArrayList();//存ArrayList数组的容器
ArrayList<Integer> array = new ArrayList<Integer>();//ArrayList数组,用来存每一层的结点
if(root == null)
return null;
last = root;//last指向根结点
nlast = null;
link.add(last);//将根结点添加到link队列
while(!link.isEmpty()){
TreeNode tn = link.removeFirst();
array.add(tn.val);//将结点值存入array数组
if(tn.left != null){
link.add(tn.left);
nlast = tn.left;
}
if(tn.right != null){
link.add(tn.right);
nlast = tn.right;
}
if(tn == last){//遍历到last就该换行了
layer.add(array);//将刚刚这层结点所在的数组array添加到ArrayList容器中
array = new ArrayList<Integer>();//将数组array置为空
last=nlast;//令last=nlast就可以将下一层存入数组了
}
}
int num[][]=new int[layer.size()][];
for(int i=0;i<layer.size();i++){
num[i]=new int[layer.get(i).size()];
for(int j=0;j<layer.get(i).size();j++){
num[i][j]=layer.get(i).get(j);
}
}
return num;
}
}
方法二:
下面这种方法,基本和第一种相同,不过第二种更加简单,直接返回容器类型,得到每一层的结点值。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// write your code here
TreeNode last;
TreeNode nlast;
LinkedList<TreeNode> link = new LinkedList<TreeNode>();//存储待打印的结点的队列
ArrayList<ArrayList<Integer>> aryary = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> array = new ArrayList<Integer>();
if(root == null)
return aryary;
last = root;
nlast = null;
link.add(root);
while(!link.isEmpty()){
TreeNode tn = link.removeFirst();
array.add(tn.val);
if(tn.left != null){
link.add(tn.left);
nlast = tn.left;
}
if(tn.right != null){
link.add(tn.right);
nlast = tn.right;
}
if(tn == last){
aryary.add(array);
array = new ArrayList<Integer>();
last = nlast;
}
}
return aryary;
}
}