forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
55 lines (41 loc) · 1.2 KB
/
main.cpp
File metadata and controls
55 lines (41 loc) · 1.2 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
54
55
/// Source : https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/
/// Author : liuyubobobo
/// Time : 2019-06-30
#include <iostream>
#include <vector>
using namespace std;
/// Mathematics
/// Time Complexity: O(log(label))
/// Space Complexity: O(log(label))
class Solution {
public:
vector<int> pathInZigZagTree(int label) {
if(label == 1) return {1};
vector<int> power2 = {1};
int e = 1;
for(int i = 1; power2.back() < label; i ++)
e *= 2, power2.push_back(power2.back() + e);
vector<int> res = {label};
bool rev = true;
for(int level = power2.size() - 2; res.back() != 1; level --){
label /= 2;
if(level && rev)
res.push_back(power2[level - 1] + 1 + power2[level] - label);
else
res.push_back(label);
rev = !rev;
}
reverse(res.begin(), res.end());
return res;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec) cout << e << " "; cout << endl;
}
int main() {
print_vec(Solution().pathInZigZagTree(14));
// 1 3 4 14
print_vec(Solution().pathInZigZagTree(26));
// 1 2 6 10 26
return 0;
}