-
Notifications
You must be signed in to change notification settings - Fork 171
/
BinaryTreeZigzagLevelOrderTraversal.java
95 lines (93 loc) · 2.91 KB
/
BinaryTreeZigzagLevelOrderTraversal.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Author: Andy, nkuwjg@gmail.com
Date: Jan 12, 2015
Problem: Binary Tree Zigzag Level Order Traversal
Difficulty: Easy
Source: https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
Notes:
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left
to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Solution: 1. Queue + reverse.
2. Two stacks.
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder_1(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
q.offer(null);
List<Integer> level = new ArrayList<Integer>();
int depth = 0;
while(true) {
TreeNode node = q.poll();
if (node != null) {
level.add(node.val);
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
} else {
if (depth % 2 == 1) Collections.reverse(level);
res.add(level);
depth++;
level = new ArrayList<Integer>();
if(q.isEmpty()==true) break;
q.offer(null);
}
}
return res;
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
Stack<TreeNode> cur = new Stack<TreeNode>();
Stack<TreeNode> last = new Stack<TreeNode>();
boolean left2right = true;
last.push(root);
List<Integer> level = new ArrayList<Integer>();
while (last.empty() == false) {
TreeNode node = last.pop();
if (node != null) {
level.add(node.val);
if (left2right) {
if(node.left!=null) cur.push(node.left);
if(node.right!=null) cur.push(node.right);
} else {
if(node.right!=null) cur.push(node.right);
if(node.left!=null) cur.push(node.left);
}
}
if (last.empty() == true) {
if (level.size() != 0)
res.add(level);
level = new ArrayList<Integer>();
Stack<TreeNode> temp = last;
last = cur;
cur = temp;
left2right = !left2right;
}
}
return res;
}
}