B. Binary-tree-array:
B. Binary-tree-array:
Just convert the string into binary notation.
ie:L to 0 and R to 1.
let that value be b in decimal.
then the answer will be 2^n+b
. where 2^n is the position of first node at height n, and b is distance between first node at height n and position of node having sequence of traversal(from root 1) as binary representation of b.
note: hidden node will be at height n.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int h, q;
cin >> h >> q;
while (q--)
{
int n;
cin >> n;
string s;
cin >> s;
string m = "";
for (int i = 0; i < n; i++)
{
if (s[i] == 'L')
m += "0";
else
m += "1";
}
int ans = stoi(m,0,2);
ans = (1 << n) | (ans);
printf("%d\n", ans);
}
return 0;
}
Left child of any node at ith position in array will be at 2*i
similarly right child will be at 2*i+1 position in same array.
So, using the given left or right information, we can recursively find position of hidden node, starting from i=1.
~~~~~
include <bits/stdc++.h>
using namespace std;
int main() { int h, q; cin >> h >> q; while (q--) { int n; cin >> n; string s; cin >> s; int ans=1; for (int i = 0; i < n; i++) { if (s[i] == 'L') ans=2*ans; else ans=2*ans+1; } printf("%d\n", ans); } return 0; } ~~~~~
C. Edge-vs-node-mapping:
C. Edge-vs-node-mapping: --------------------- Tree has one property that all the nodes except root node will have exactly one parent node.
So for all node except root node, we can map the node with edge connecting it with it's parent node.
This can be done with dfs with assuming some random node root.
#include <bits/stdc++.h>
using namespace std;
void dfs(int root, int par, vector<int> arr[])
{
for (auto &x : arr[root])
{
if (x == par)
continue;
printf("%d %d %d\n", x, root, x); // root is parent of x, so mapping them
dfs(x, root, arr);
}
}
int main()
{
int n;
scanf("%d", &n);
vector<int> arr[n + 1];
for (int i = 1; i <= n - 1; i++)
{
int a, b;
scanf("%d %d", &a, &b);
arr[a].push_back(b);
arr[b].push_back(a);
}
dfs(1, -1, arr); // choosing 1 as root
return 0;
}
Same logic is used , but instead of doing dfs, we can do bottom up approach from leaf nodes to parent, as shown in below code.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
vector<set<int>> arr(n + 1);
for (int i = 1; i <= n - 1; i++)
{
int a, b;
scanf("%d %d", &a, &b);
arr[a].insert(b);
arr[b].insert(a);
}
// vector<int> visited(n + 1, 0);
queue<int> leaf;
// visited[1] = 1;
for (int i = 1; i <= n; i++)
if (arr[i].size() == 1)
leaf.push(i);
while (leaf.size() != 0)
{
int x = leaf.front();
leaf.pop();
if (x == 1)
continue;
assert(arr[x].size() == 1);
int par = *arr[x].begin();
printf("%d %d %d\n", x, par, x);
arr[par].erase(x);
// arr[x].erase(par);
if (arr[par].size() == 1)
leaf.push(par);
}
return 0;
}