按之字形层序遍历二叉树
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
/*
* @Author helen
* @Date 2021/4/10 9:16
* @Descriptions
* 题目描述
* 给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
*/
import java.util.ArrayList;
import java.util.Stack;
public class 按之子形遍历二叉树 {
public ArrayList<ArrayList<Integer>> zigzagLevelOrder (BTreeNode<Integer> root) {
// write code here
ArrayList<ArrayList<Integer>> list2 = new ArrayList<>();
if(root == null)
return list2;
Stack<BTreeNode<Integer>> stack[] = new Stack[2]; //用两个栈,一个存储奇数层结点,一个用来存储偶数层结点
stack[0] = new Stack<BTreeNode<Integer>>(); //需要初始化栈,否则默认为null,则会push时报NullPointException
stack[1] = new Stack<BTreeNode<Integer>>();
int current = 0;
int next = 1;
stack[current].push(root);
while(!stack[0].isEmpty() || !stack[1].isEmpty()){
ArrayList<Integer> list1 = new ArrayList<>();
while(!stack[current].isEmpty()) {
BTreeNode<Integer> node = stack[current].pop();
list1.add(node.data);
if (current == 0) { //若为偶数层,则其左子结点先入栈,右子结点后入栈,以便下一层右边的结点先遍历
if (node.left != null)
stack[next].push(node.left);
if (node.right != null)
stack[next].push(node.right);
}
if (current == 1) { //若为奇数层,则其右子结点先入栈,左子结点后入栈,以便下一层左边的结点先遍历
if (node.right != null)
stack[next].push(node.right);
if (node.left != null)
stack[next].push(node.left);
}
}
current = 1 - current;
next = 1 - next;
list2.add(list1);
}
return list2;
}
public static void main(String[] args) {
按之子形遍历二叉树 obj = new 按之子形遍历二叉树();
BTree<Integer> bTree = new BTree<>();
for (int i = 0; i < 10; i++) {
bTree.RandomCreatTree(bTree.root, i);
}
System.out.println("==============按之子形遍历二叉树=================");
System.out.println(obj.zigzagLevelOrder(bTree.root).toString());
}
}