JZ60 把二叉树打印成多行
把二叉树打印成多行
http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
解法一:分隔节点
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
Queue<TreeNode> q=new LinkedList<>();
ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
ArrayList<Integer> l=new ArrayList<>();
if(pRoot==null) {
return ans;
}
q.add(pRoot);
TreeNode split=new TreeNode(0);
q.add(split);
while(q.size()!=1){
TreeNode curr=q.poll();
if(curr==split){
ans.add(l);
l=new ArrayList<>();
q.add(split);
continue;
}
l.add(curr.val);
if(curr.left!=null) q.add(curr.left);
if(curr.right!=null) q.add(curr.right);
}
if(l.size()!=0) ans.add(l);
return ans;
}
}解法二:BFS+记录深度
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
if(pRoot==null) return ans;
Queue<TreeNode> q=new LinkedList<>();
q.add(pRoot);
int level=0;
while(!q.isEmpty()){
ans.add(new ArrayList<Integer>());
int size=q.size();
while(size-->0){
TreeNode curr=q.poll();
ans.get(level).add(curr.val);
if(curr.left!=null) q.add(curr.left);
if(curr.right!=null) q.add(curr.right);
}
level++;
}
return ans;
}
}解法三:DFS+记录深度
略


