题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list=new ArrayList<>();
dfs(pRoot,1,list);
for (int i = 0; i < list.size(); i++) {
if(i%2!=0){
ArrayList<Integer> temp=list.get(i);
Collections.reverse(temp);
list.set(i,temp);
}
}
return list;
}
public void dfs(TreeNode pRoot,int depth,ArrayList<ArrayList<Integer>> list){
if(pRoot==null) return;
if(depth>list.size()) list.add(new ArrayList<>());
list.get(depth-1).add(pRoot.val);
dfs(pRoot.left,depth+1,list);
dfs(pRoot.right,depth+1,list);
}
}
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list=new ArrayList<>();
dfs(pRoot,1,list);
for (int i = 0; i < list.size(); i++) {
if(i%2!=0){
ArrayList<Integer> temp=list.get(i);
Collections.reverse(temp);
list.set(i,temp);
}
}
return list;
}
public void dfs(TreeNode pRoot,int depth,ArrayList<ArrayList<Integer>> list){
if(pRoot==null) return;
if(depth>list.size()) list.add(new ArrayList<>());
list.get(depth-1).add(pRoot.val);
dfs(pRoot.left,depth+1,list);
dfs(pRoot.right,depth+1,list);
}
}