思路:两个栈s1和s2,遍历s1时按左到右顺序在s2存放子树根节点,遍历s2时按从右到左顺序在s1存放子树根节点
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
if(pRoot == null) return listAll;
Stack<TreeNode> s1 = new Stack();//栈
Stack<TreeNode> s2 = new Stack();
TreeNode p = null;
s1.push(pRoot);
while(!s1.isEmpty() || !s2.isEmpty()){
ArrayList<Integer> list = new ArrayList<>();
while(!s1.isEmpty()){
p = s1.pop();
list.add(p.val);
if(p.left != null)s2.push(p.left);
if(p.right != null)s2.push(p.right);
}
if(!list.isEmpty())listAll.add(list);
list = new ArrayList<>();
while(!s2.isEmpty()){
p = s2.pop();
list.add(p.val);
if(p.right != null)s1.push(p.right);
if(p.left != null)s1.push(p.left);
}
if(!list.isEmpty())listAll.add(list);
}
return listAll;
}
}