Created
April 29, 2014 23:59
-
-
Save gabhi/bb9056a2604a1208017e to your computer and use it in GitHub Desktop.
Print ancestors of an element in tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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