题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解题思路
在打印根节点的时候,它的左节点和右节点需要先保存到一个容器里面,在打印第二层节点的时候,先打印右节点后打印左节点。因为节点在该容器中是后进先出的,所以该数据容器可以使用栈来实现:
1、首先需要两个栈,分别用于保存奇数层和偶数层节点
2、打印某一层时,把下一层对应的子节点保存到栈里;
3、如果当前打印的为奇数层,则先保存右节点再保存左节点到第一个栈中;
4、如果当前打印的为偶数层,则先保存左节点再保存右节点到第一个栈中;
参考代码
import java.util.ArrayList;
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 static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot){
int layer = 1;
Stack<TreeNode> stack1 = new Stack<TreeNode>(); // stack1用于保存奇数层节点
Stack<TreeNode> stack2 = new Stack<TreeNode>(); // stack2用于保存偶数层节点
stack1.push(pRoot);
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
while(!stack1.isEmpty() || !stack2.isEmpty()) {
if (layer%2 != 0) {
ArrayList<Integer> temp = new ArrayList<Integer>();
while(!stack1.isEmpty()) {
TreeNode node = stack1.pop();
if (node != null) {
temp.add(node.val);
System.out.print(node.val + " ");
stack2.push(node.left);
stack2.push(node.right);
}
}
if (!temp.isEmpty()) {
list.add(temp);
layer ++;
System.out.println();
}
}else {
ArrayList<Integer> temp = new ArrayList<Integer>();
while(!stack2.isEmpty()) {
TreeNode node = stack2.pop();
if (node != null) {
temp.add(node.val);
System.out.print(node.val + " ");
stack1.push(node.right);
stack1.push(node.left);
}
}
if (!temp.isEmpty()) {
list.add(temp);
layer ++;
System.out.println();
}
}
}
return list;
}
} 栈