题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
Solution
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Stack;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
Stack[] stacks = new Stack[2];
stacks[0] = new Stack<TreeNode>();
stacks[1] = new Stack<TreeNode>();
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
int current = 0;
int next = 1;
if(pRoot == null)
return lists;
stacks[current].push(pRoot);
ArrayList<Integer> list = new ArrayList<Integer>();
while(!stacks[0].empty() || !stacks[1].empty()){
pRoot = (TreeNode)stacks[current].pop();
list.add(pRoot.val);
if(current == 0){
//当前打印的是奇数层,先保存左子节点,在保存右子节点
//保存的是偶数层的结点,在偶数层输出,打印的顺序是从右到左
if(pRoot.left != null)
stacks[next].push(pRoot.left);
if(pRoot.right != null)
stacks[next].push(pRoot.right);
}else{
//当前打印的是偶数层,先保存右子节点,在保存左子节点
//保存的是奇数层的结点,在奇数层输出,打印的顺序是从左到右
if(pRoot.right != null)
stacks[next].push(pRoot.right);
if(pRoot.left != null)
stacks[next].push(pRoot.left);
}
//当前层已经打印完毕,切换奇偶性
if(stacks[current].empty()){
current = 1 - current;
next = 1 - next;
lists.add(list);
list = new ArrayList<Integer>();
}
}
return lists;
}
}