# JZ-059 - Print binary tree in zigzag order

#### Topic description

Please implement a function to print the binary tree in a zigzag pattern, that is, the first line is printed in left-to-right order, the second layer is printed in right-to-left order, the third line is printed in left-to-right order, and the other lines are printed in order from left to right. And so on.

title link : print binary tree in zigzag order

#### code

``````import java.util.ArrayList;
import java.util.Queue;
import java.util.Stack;

/**
* 标题：按之字形顺序打印二叉树
* 题目描述
* 请实现一个函数按照之字形打印二叉树，即第一行按照从左到右的顺序打印，第二层按照从右至左的顺序打印，第三行按照从左到右的顺序打印，其他行以此类推。
* 题目链接：
* https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=13&&tqId=11212&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
*/
public class Jz59 {

public ArrayList<ArrayList<Integer>> print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
boolean flag = true; // 当flag为true时，栈从左向右放；当flag为false时，栈从右向左放
while (!treeNodes.isEmpty()) {
int cnt = treeNodes.size();
ArrayList<Integer> curList = new ArrayList<>();
Stack<TreeNode> curNodes = new Stack<>();
while (cnt-- > 0) {

TreeNode t = treeNodes.poll();
if (t == null) {
continue;
}
if (flag) {
} else {
}
}
flag = !flag;
while (!curNodes.isEmpty()) {
}
if (!curList.isEmpty()) {
}
}
return result;
}

public static void main(String[] args) {

}
}``````
[Daily Message] As long as you work harder today, the person who can shine like a star in the future is you!

1.7k 声望
7.1k 粉丝
0 条评论