-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPathInZigZagBinaryTree.java
36 lines (30 loc) · 1.02 KB
/
PathInZigZagBinaryTree.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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PathInZigZagBinaryTree {
public static List<Integer> pathInZigZagTree(int label) {
List<Integer> ls = new ArrayList<>();
ls.add(label);
while (true) {
int logicalParent = Math.floorDiv(label, 2);
int levelOfLabel = (int) (Math.log(label) / Math.log(2));
if (levelOfLabel <= 1) {
if (levelOfLabel != 0) {
ls.add(1);
}
break;
}
int levelOfParent = levelOfLabel - 1;
int minOfParent = (int) Math.pow(2, levelOfParent);
int maxOfParent = (minOfParent * 2) - 1;
if (levelOfLabel % 2 == 0) {
label = maxOfParent - (logicalParent - minOfParent);
} else {
label = minOfParent + (maxOfParent - logicalParent);
}
ls.add(label);
}
Collections.reverse(ls);
return ls;
}
}