Problem: Given a Binary tree and a node’s value, Write a function to print all the ancestors of the node.
Thinking of solution??Think Recursively.This problem can be easily solved using recursion. We start from the root of the tree and keep going down the tree. When we reach the node with given value we return true.if a node contains the given node in left or right subtree we print it and return true to it’s parent till we reach root.
struct node { int data; struct node; }; bool printAncestors(struct node* root,int value) { if(root==NULL) return false; if(root->data == value) return true; if(printAncestors(root->left,value)||printAncestors(root->right,value)) { cout<<root->data<<" "; return true; } return false; }
void printAllAncestors(node *n) {
if (!n)
return;
else {
cout<val<par);
}
}