【题目描述】从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
【解题思路】层序遍历二叉树,依次打印出每层节点,遇到空节点跳过。
//非递归
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> arrs = new ArrayList<ArrayList<Integer>>();
if(pRoot == null){
return arrs;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(pRoot);
int last=q.size(), count=0;
while(!q.isEmpty()){
count = 0;
last = q.size();
ArrayList<Integer> arr = new ArrayList<Integer>();
while(count<last){
TreeNode tr = q.poll();
count++;
arr.add(tr.val);
if(tr.left != null){
q.add(tr.left);
}
if(tr.right != null){
q.add(tr.right);
}
}
arrs.add(arr);
}
return arrs;
}
}
//递归
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
depth(pRoot, 1, list);
return list;
}
private void depth(TreeNode root, int depth, ArrayList<ArrayList<Integer>> list) {
if(root == null) return;
if(depth > list.size())
list.add(new ArrayList<Integer>());
list.get(depth -1).add(root.val);
depth(root.left, depth + 1, list);
depth(root.right, depth + 1, list);
}
}