|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
| 4 | +import com.fishercoder.common.utils.CommonUtils; |
4 | 5 | import com.fishercoder.common.utils.TreeUtils;
|
5 | 6 |
|
6 |
| -import java.lang.reflect.Array; |
7 | 7 | import java.util.ArrayList;
|
| 8 | +import java.util.Arrays; |
8 | 9 | import java.util.Collections;
|
9 | 10 | import java.util.Deque;
|
10 | 11 | import java.util.LinkedList;
|
@@ -36,6 +37,7 @@ public static class Solution1 {
|
36 | 37 | /**This brute force solution is correct but results in TLE on LeetCode.*/
|
37 | 38 | public List<Integer> pathInZigZagTree(int label) {
|
38 | 39 | Deque<Integer> deque = buildZigZagOrderList(label);
|
| 40 | + CommonUtils.printDeque(deque); |
39 | 41 | TreeNode root = buildZigZagOrderTree(deque);
|
40 | 42 | TreeUtils.printBinaryTree(root);
|
41 | 43 | return dfs(root, label, new ArrayList<>());
|
@@ -97,4 +99,55 @@ private Deque<Integer> buildZigZagOrderList(int label) {
|
97 | 99 | return deque;
|
98 | 100 | }
|
99 | 101 | }
|
| 102 | + |
| 103 | + public static class Solution2 { |
| 104 | + /**We'll directly compute the index of its parent, it'll be much faster this way.*/ |
| 105 | + public List<Integer> pathInZigZagTree(int label) { |
| 106 | + List<List<Integer>> lists = buildZigZagOrderList(label); |
| 107 | + CommonUtils.printListList(lists); |
| 108 | + List<Integer> result = new ArrayList<>(); |
| 109 | + int index = findIndex(lists.get(lists.size() - 1), label); |
| 110 | + result.add(label); |
| 111 | + for (int i = lists.size() - 2; i >= 0; i--) { |
| 112 | + index /= 2; |
| 113 | + result.add(lists.get(i).get(index)); |
| 114 | + } |
| 115 | + Collections.sort(result); |
| 116 | + return result; |
| 117 | + } |
| 118 | + |
| 119 | + private int findIndex(List<Integer> level, int label) { |
| 120 | + for (int i = 0; i < level.size(); i++) { |
| 121 | + if (level.get(i) == label) { |
| 122 | + return i; |
| 123 | + } |
| 124 | + } |
| 125 | + return -1; |
| 126 | + } |
| 127 | + |
| 128 | + private List<List<Integer>> buildZigZagOrderList(int label) { |
| 129 | + List<List<Integer>> lists = new ArrayList<>(); |
| 130 | + int num = 1; |
| 131 | + int level = 2; |
| 132 | + lists.add(Arrays.asList(num)); |
| 133 | + if (label == 1) { |
| 134 | + return lists; |
| 135 | + } |
| 136 | + List<Integer> newLevel = new ArrayList<>(); |
| 137 | + do { |
| 138 | + newLevel.clear(); |
| 139 | + num++; |
| 140 | + for (; num < Math.pow(2, level); num++) { |
| 141 | + newLevel.add(num); |
| 142 | + } |
| 143 | + num--; |
| 144 | + if (level % 2 == 0) { |
| 145 | + Collections.reverse(newLevel); |
| 146 | + } |
| 147 | + lists.add(new ArrayList<>(newLevel)); |
| 148 | + level++; |
| 149 | + } while (newLevel.get(0) < label && newLevel.get(newLevel.size() - 1) < label); |
| 150 | + return lists; |
| 151 | + } |
| 152 | + } |
100 | 153 | }
|
0 commit comments