把二叉树打印成多行
题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路:
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode ppRootOfTree) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
depth(ppRootOfTree, 1, list);
return list;
}
private void depth(TreeNode pRootOfTree, int depth, ArrayList<ArrayList<Integer>> list) {
if(pRootOfTree == null) return;
if(depth > list.size())
list.add(new ArrayList<Integer>());
list.get(depth -1).add(pRootOfTree.val);
depth(pRootOfTree.left, depth + 1, list);
depth(pRootOfTree.right, depth + 1, list);
}
}
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode ppRootOfTree) {
ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
if(ppRootOfTree==null){//注意判断
return list;
}
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(ppRootOfTree);
int num = 1;// 表示当前lever层上的结点个数
while(!queue.isEmpty()){// 队列非空
int nextNum = 0;// 临时变量,用来记录下一层的结点个数
ArrayList<Integer> list_list=new ArrayList<Integer>();
// 取出当前层并打印,随后加入下一层的结点
for(int i=0;i<num;i++){
TreeNode node=queue.poll();// 取出队列头
list_list.add(node.val);
// 左孩子不为空
if(node.left!=null){
queue.add(node.left);
nextNum++;
}
// 右孩子不为空
if(node.right!=null){
queue.add(node.right);
nextNum++;
}
}
num=nextNum;
list.add(list_list);
}
return list;
}
}