题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
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 {
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
if(pRoot == null) return new ArrayList<>();
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
TreeNode node;
stack1.push(pRoot);
while(!stack1.isEmpty() || !stack2.isEmpty()){
ArrayList<Integer> list1 = new ArrayList<>();
while(!stack1.isEmpty()){
node = stack1.pop();
list1.add(node.val);
if(node.left != null) stack2.push(node.left);
if(node.right != null) stack2.push(node.right);
}
if(!list1.isEmpty()) res.add(list1);
ArrayList<Integer> list2 = new ArrayList<>();
while(!stack2.isEmpty()){
node = stack2.pop();
list2.add(node.val);
if(node.right != null) stack1.push(node.right);
if(node.left != null) stack1.push(node.left);
}
if(!list2.isEmpty()) res.add(list2);
}
return res;
}
}