Do a preorder traversal
if you find anyone of the node then find the other node in the subtree whose root is the first found node.
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
bool isPresent(node* node,int n){ | |
if(node==NULL) | |
return false; | |
if(node->data==n) | |
return true; | |
return isPresent(node->left,n)||isPresent(node->right,n); | |
} | |
bool isBothNodesinSamePathFromRoot(node* node,int n1,int n2){ | |
if(node==NULL) | |
return false; | |
if(node->data==n1) | |
return isPresent(node,n2); | |
if(node->data==n2) | |
return isPresent(node,n1); | |
return isBothNodesinSamePathFromRoot(node->left,n1,n2)||isBothNodesinSamePathFromRoot(node->right,n1,n2); | |
} |