请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
分析:按之字形打印需要两个栈,我们打印某一层的节点时,拔下一层的子节点保存到相应的栈中。如果当前打印的是奇数层,那么则先保存左子节点再右子节点,如果当前打印的是偶数层那么,则先保存右子节点再左子节点。
public class Solution {
//行数
int count=0;
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result=new ArrayList<>();
if(pRoot==null){
return result;
}
Stack<TreeNode> s1=new Stack<>();
Stack<TreeNode> s2=new Stack<>();
s1.push(pRoot);
while(!s1.isEmpty()||!s2.isEmpty()){
count++;
ArrayList<Integer> temp=new ArrayList<>();
if(count%2==1){
while(!s1.isEmpty()){
TreeNode node=s1.pop();
if(node!=null){
s2.push(node.left);
s2.push(node.right);
temp.add(node.val);
}
}
if(!temp.isEmpty()){
count++;
result.add(temp);
}
}else{
while(!s2.isEmpty()){
TreeNode node=s2.pop();
if(node!=null){
s1.push(node.right);
s1.push(node.left);
temp.add(node.val);
}
}
if(!temp.isEmpty()){
count++;
result.add(temp);
}
}
}
return result;
}
}