1.树从上至下按层打印,同层节点从左至右打印
class Solution {
public int[] levelOrder(TreeNode root) {
if(root==null){return new int[0];}
List<Integer> list=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node=queue.poll();
list.add(node.val);
if(node.left!=null){queue.add(node.left);}
if(node.right!=null){queue.add(node.right);}
}
int[] res=new int[list.size()];
for(int i=0;i<list.size();i++){
res[i]=list.get(i);
}
return res;
}
}
2.树按层打印且每一层打印到一行
class Solution {
List<List<Integer>> res;
public List<List<Integer>> levelOrder(TreeNode root) {
res=new ArrayList<>();
dfs(root,0);
return res;
}
public void dfs(TreeNode root,int depth){
if(root==null){return;}
if(res.size()==depth){res.add(new ArrayList<>());}
res.get(depth).add(root.val);
dfs(root.left,depth+1);
dfs(root.right,depth+1);
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
if(root==null){return res;}
queue.add(root);
while(!queue.isEmpty()){
List<Integer> tmp=new ArrayList<>();
for(int i=queue.size();i>0;i--){
root=queue.poll();
tmp.add(root.val);
if(root.left!=null){queue.add(root.left);}
if(root.right!=null){queue.add(root.right);}
}
res.add(tmp);
}
return res;
}
}
3.树按层打印且奇数层正序,偶数层倒序(之字打印)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
if(root==null){return res;}
while(!queue.isEmpty()){
List<Integer> list=new ArrayList<>();
for(int i=queue.size();i>0;i--){
root=queue.poll();
list.add(root.val);
if(root.left!=null){queue.add(root.left);}
if(root.right!=null){queue.add(root.right);}
}
if((res.size()&1)==1){Collections.reverse(list);}
res.add(list);
}
return res;
}
}
class Solution {
List<List<Integer>> res;
public List<List<Integer>> levelOrder(TreeNode root) {
res=new ArrayList<>();
dfs(root,0);
return res;
}
public void dfs(TreeNode root,int depth){
if(root==null){return;}
if(res.size()==depth){
res.add(new ArrayList<>());
}
if((depth&1)==0){res.get(depth).add(root.val);}
if((depth&1)==1){res.get(depth).add(0,root.val);}
dfs(root.left,depth+1);
dfs(root.right,depth+1);
}
}