题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
奇数行用队列实现
偶数行用栈实现
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/*
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) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if(pRoot == null) return list;
int index = 1;
Queue<TreeNode> queue =new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
queue.offer(pRoot);
while(!queue.isEmpty()){
ArrayList<Integer> a =new ArrayList<>();
if(index%2 == 1){
int size = queue.size();
for(int i = 0;i < size;i++){
TreeNode node = queue.poll();
a.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}}else{
int size = queue.size();
for(int i = 0;i < size;i++){
TreeNode node = queue.poll();
stack.push(node);
if(i == size -1){
while(!stack.empty()){
a.add(stack.pop().val);
}
}
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
list.add(a);
index++;
}
return list;
}
}