-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZigzagBTPath.cpp
84 lines (83 loc) · 2.23 KB
/
ZigzagBTPath.cpp
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
/*
* In an infinite binary tree where every node has two children, the nodes are labelled in row order.
* In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
* Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.
*/
#include <vector>
using namespace std;
vector<int> path_helperEven(int root, int label, int start, int end)
{
// cout << root << " " << start << " " << end << endl;
vector<int> path;
if (root == label)
{
path.push_back(root);
return path;
}
else if (root > label)
{
return path;
}
else
{
int right = (2 * end + 1) - 2 * (root - start);
int left = right - 1;
path = path_helperOdd(left, label, end + 1, 2 * end + 1);
if (!path.empty())
{
path.push_back(root);
return path;
}
path = path_helperOdd(right, label, end + 1, 2 * end + 1);
if (!path.empty())
{
path.push_back(root);
return path;
}
return path;
}
}
vector<int> path_helperOdd(int root, int label, int start, int end)
{
// cout << root << " " << start << " " << end << endl;
vector<int> path;
if (root == label)
{
path.push_back(root);
return path;
}
else if (root > label)
{
return path;
}
else
{
int left = (2 * end + 1) - 2 * (root - start);
int right = left - 1;
path = path_helperEven(left, label, end + 1, 2 * end + 1);
if (!path.empty())
{
path.push_back(root);
return path;
}
path = path_helperEven(right, label, end + 1, 2 * end + 1);
if (!path.empty())
{
path.push_back(root);
return path;
}
return path;
}
}
vector<int> pathInZigZagTree(int label)
{
vector<int> path = path_helperOdd(1, label, 1, 1);
vector<int> ret;
int size = path.size();
for (int i = 0; i < size; ++i)
{
ret.push_back(path.back());
path.pop_back();
}
return ret;
}