-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2415.java
More file actions
53 lines (48 loc) · 1.59 KB
/
LC2415.java
File metadata and controls
53 lines (48 loc) · 1.59 KB
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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.tree.TreeNode;
public class LC2415 {
public static TreeNode reverseOddLevels(TreeNode root) {
// Base Case
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int level = 0;
// While queue is not empty
while (!queue.isEmpty()) {
int size = queue.size();
ArrayList<TreeNode> list = new ArrayList<>();
// Level of traversal
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) { // if have an left node insert into queue
queue.offer(node.left);
}
if (node.right != null) { // if have an right node insert into queue
queue.offer(node.right);
}
if (level % 2 != 0) { // if have odd nodes
list.add(node);
}
}
if (level % 2 != 0) {
// two pointer approach
int r = 0;
int l = list.size() - 1;
while (r < l) {
// if right less than left then swap it nodes
int temp = list.get(r).val;
list.get(r).val = list.get(l).val;
list.get(l).val = temp;
r++;
l--;
}
}
level++;
}
return root;
}
}