Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created April 29, 2014 23:59
Show Gist options
  • Save gabhi/bb9056a2604a1208017e to your computer and use it in GitHub Desktop.
Save gabhi/bb9056a2604a1208017e to your computer and use it in GitHub Desktop.
Print ancestors of an element in tree
/* If target is present in tree, then prints the ancestors
and returns true, otherwise returns false. */
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment