-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution32_3.java
44 lines (34 loc) · 1.15 KB
/
Solution32_3.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.usher.algorithm.offer;
import java.util.*;
/**
* @Author: Usher
* @Description: 之字形打印二叉树
* 第一行按照从左到右打印的顺序,第二层按照从右到左的顺序打印,第三行按照从左到右的顺序
*/
public class Solution32_3 {
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if (pRoot == null)
return ret;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
boolean reverse = false;
while (!queue.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
int cnt = queue.size();
for (int i = 0;i < cnt;i++){
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
if (reverse)
Collections.reverse(list);
reverse = !reverse;
ret.add(list);
}
return ret;
}
}