题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
题解:
使用两个栈,一个栈用于存放当前节点,一个栈用于存放当前节点的子节点
package com.sunny.offer;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class treeNode1 {
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
System.out.println(Print(node1));
}
public static ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
if(pRoot == null){
return res;
}
stack1.add(pRoot);
while(stack1.size() >0||stack2.size()>0){
ArrayList<Integer> list = new ArrayList<Integer>();
if(stack1.size()>0){
int len = stack1.size();
for(int i = 0;i<len;i++){
TreeNode treeNode = stack1.pop();
list.add(treeNode.val);
if(treeNode.left !=null){
stack2.add(treeNode.left);
}
if(treeNode.right !=null){
stack2.add(treeNode.right);
}
}
res.add(list);
continue;
}
if(stack2.size()>0){
int len = stack2.size();
for(int i = 0;i<len;i++){
TreeNode treeNode = stack2.pop();
list.add(treeNode.val);
if(treeNode.right !=null){
stack1.add(treeNode.right);
}
if(treeNode.left !=null){
stack1.add(treeNode.left);
}
}
res.add(list);
continue;
}
}
return res;
}
}