剑指offer算法题
栈 树
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
题目分析
方法一 利用两个栈
利用一个栈作为奇数层的栈,另一个作为偶数层的栈,利用栈的先入后出原理向ArrayList中添加数组。
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 ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer>>();
if(pRoot == null){
return result;
}
Stack<TreeNode> s = new Stack<>();
Stack<TreeNode> s2= new Stack<>();
int count = 0 , nextCount = 1 , depth =0;
s.push(pRoot);
ArrayList<Integer> countResult = new ArrayList<>();
TreeNode tmp = null;
while(!s.isEmpty()||!s2.isEmpty() ){
if(depth %2 ==1&&s2.peek()!=null){
tmp = s2.pop();
if(tmp.right!=null){
s.push(tmp.right);
}
if(tmp.left!=null){
s.push(tmp.left);
}
}else if(depth %2==0&& s.peek()!=null){
tmp = s.pop();
if(tmp.left!=null){
s2.push(tmp.left);
}
if(tmp.right!=null){
s2.push(tmp.right);
}
}
++count;
countResult.add(tmp.val);
if(count == nextCount){
count = 0;
if(depth %2 == 0){
nextCount = s2.size();
}else{
nextCount = s.size();
}
result.add(countResult);
++depth;
countResult = new ArrayList<>();
}
}
return result;
}
}
方法二 反转list
按照题意,首先层次遍历,然后遇到奇数层将该层的ArrayList进行反转。
该方法效率很低,不推荐。
下面是JAVA算法实现:
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;
import java.util.Collections;
/*
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;
}
Queue<TreeNode> q = new LinkedList<>();
int count = 0 , nextCount = 1 , depth =0;
q.offer(pRoot);
ArrayList<Integer> countResult = new ArrayList<>();
while(!q.isEmpty()){
TreeNode tmp = q.poll();
++count;
countResult.add(tmp.val);
if(tmp.left!=null){
q.offer(tmp.left);
}
if(tmp.right!=null){
q.offer(tmp.right);
}
if(count == nextCount){
count = 0;
nextCount = q.size();
if(depth %2 ==0){
result.add(countResult);
}else if(depth %2 ==1){
result.add(reverse(countResult));
//也可以直接用Collections的reverse方法。
//Collections.reverse(countResult);
//result.add(countResult);
}
++depth;
countResult = new ArrayList<>();
}
}
return result;
}
private ArrayList<Integer> reverse(ArrayList<Integer> list){
int left = 0;
int right = list.size()-1;
int tmp = -1;
while(left <right ){
tmp = list.get(left);
list.set(left,list.get(right)) ;
list.set(right,tmp) ;
++left;
--right;
}
return list;
}
}