If target is present in tree, then prints all the ancestors and returns true,
otherwise returns false.
1
/ \
2 3
/ \
4 5
/
7
key is 7, then your function should print 4, 2 and 1.
bool printAncestors(struct node *root, int target){ /* base cases */ if (root == NULL) return false; if (root->data == target) return true; /* If target is present in either left or right subtree of this node, then print this node */ if ( printAncestors(root->left, target) || printAncestors(root->right, target) ){ cout << root->data << "␣"; return true; } /* Else return false */ return false; }
Idea: just like max height example, return bool instead value, logic
|| instead max. the basic idea are quite same.