问题描述:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:
1、需要借助两个堆栈stack1,stack2。
2、stack1用于记录奇数层的节点数,stack2用于记录偶数层的节点数。
3、开始时先将头节点放入stack1中,并将stack1中的节点弹出的同时,将弹出节点的左右子节点存入stack2中(先存左节点再存右节点),弹出的节点存入list集合中。stack1弹空后,开始弹出stack2中的元素,将弹出节点的左右子节点存入stack1中(先存右节点,再存左节点),弹出的节点存入list集合中,以此类推。
代码:
import java.util.*;
/*
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>> res = new ArrayList<ArrayList<Integer>>();
if(pRoot == null){
return res;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.add(pRoot);
while(!stack1.isEmpty() || !stack2.isEmpty()){
if(!stack1.isEmpty()){
ArrayList<Integer> sup = new ArrayList<>();
while(!stack1.isEmpty()){
TreeNode p = stack1.pop();
if(p.left != null){
stack2.add(p.left);
}
if(p.right != null){
stack2.add(p.right);
}
sup.add(p.val);
}
res.add(sup);
}else{
ArrayList<Integer> sup = new ArrayList<>();
while(!stack2.isEmpty()){
TreeNode p = stack2.pop();
if(p.right != null){
stack1.add(p.right);
}
if(p.left != null){
stack1.add(p.left);
}
sup.add(p.val);
}
res.add(sup);
}
}
return res;
}
}
左神版代码:
import java.util.*;
/*
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>> result = new ArrayList<ArrayList<Integer>>();
if(pRoot == null){
return result;
}
Deque<TreeNode> dq = new LinkedList<>();
ArrayList<Integer> list = new ArrayList<Integer>();
boolean lr = true;
TreeNode last = pRoot;
TreeNode nLast = null;
dq.offerFirst(pRoot);
while(!dq.isEmpty()){
if(lr){
pRoot = dq.pollFirst();
list.add(pRoot.val);
if(pRoot.left != null){
nLast = nLast == null ? pRoot.left : nLast;
dq.offerLast(pRoot.left);
}
if(pRoot.right != null){
nLast = nLast == null ? pRoot.right : nLast;
dq.offerLast(pRoot.right);
}
}else{
pRoot = dq.pollLast();
list.add(pRoot.val);
if(pRoot.right != null){
nLast = nLast == null ? pRoot.right : nLast;
dq.offerFirst(pRoot.right);
}
if(pRoot.left != null){
nLast = nLast == null ? pRoot.left : nLast;
dq.offerFirst(pRoot.left);
}
}
if(pRoot == last){
lr = !lr;
last = nLast;
nLast = null;
result.add(list);
list = new ArrayList<Integer>();//复用
}
}
return result;
}
}