思路:使用两个栈,从stackOut弹出结点并添加到当前层,将该结点的孩子结点按照下一轮打印顺序压入stackIn。
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
if(pRoot==null) return new ArrayList<>();
ArrayList<ArrayList<Integer>> answer=new ArrayList<>();
Stack<TreeNode> stack1=new Stack<>();
Stack<TreeNode> stack2=new Stack<>();
//两个栈与打印方向
Stack<TreeNode> stackOut=null;
Stack<TreeNode> stackIn=null;
boolean dirctionFlag=false;//false代表下一轮从右向左打印
//tmp val
TreeNode node=null;
stack1.push(pRoot);
while(!(stack1.empty()&&stack2.empty())){
ArrayList<Integer> currentFloor=new ArrayList<>();
stackOut=stack1.empty()?stack2:stack1;
stackIn=stack1.empty()?stack1:stack2;
//一轮打印
while(!stackOut.empty()){
node=stackOut.pop();
currentFloor.add(node.val);
if(dirctionFlag) {
if(node.right!=null) stackIn.push(node.right);
if(node.left!=null) stackIn.push(node.left);
}
else{
if(node.left!=null) stackIn.push(node.left);
if(node.right!=null) stackIn.push(node.right);
}
}
answer.add(currentFloor);
dirctionFlag=!dirctionFlag;
}
return answer;
}