Recently I read some interview questions on gfg of amazon sde-1 , and this question has no solution till now , so asked here , the q. is :
Print all three nodes in a binary tree such that sum of all these three nodes is greater than given x and these three nodes must hold the relationship of grandparent-parent-child.
I think you could also maintain the stack of your ancestors in a DFS and, whenever the number of ancestors \ge 2, sum the current node’s value plus that of the two most recent ancestors and see if this sum > x.
Very simple solution :
Just make an array pointing to parent of every node.
Meaning,
array[k] = parent of node k
Now for each node k find sum of Val[k]+Val[array[k]] + Val[array[array[k]]]
Assuming grandparent is immediate parent of parent and parent is immediate parent of child
void solve(Node* root, int d)
{
if(root == NULL)
return;
int x, gp, p;
x = root->val;
p = parent[x];
gp = parent[p];
if(x + p + gp > x and d >= 3)
cout << gp << ' ' << p << ' ' << x << endl;
solve(root->left, d+1);
solve(root->right, d+1);
}