Wednesday, 14 September 2011

Nearest common Ancestor Given a binary tree(not a BST), you need to find the Nearest common ancestor of the two given values.



/* InOrder Traversal Left ==> ROOT ==> RIGHT , hence the NCA of 2 nodes should be inbetween the 2 nodes in the vector. PostOrder traversal LEFT ==> RIGHT ==> ROOT , hence the NCA is the leftmost in postOrder vector of all the elements found inbetween in INOrder vector */ int nca(BinaryTreeIntNode* node,int n1,int n2) { if(node == NULL) { return -1; } int nca = -1; std::vector* vectInorder = new std::vector(); std::vector* vectPost = new std::vector(); InOrderRecVector(node,vectInorder);//get the inOrder traversal in a Vector postOrderRecVector(node,vectPost);//get the postOrder traversal in a Vector int tempIndex = 0; int index1 = std::find(vectInorder->begin(),vectInorder->end(),n1) - vectInorder->begin(); int index2 = std::find(vectInorder->begin(),vectInorder->end(),n2) - vectInorder->begin(); int i = (index1>index2?index1:index2); int j = (index1>index2?index2:index1); for(i; i >= j;i--) { tempIndex = std::find(vectPost->begin(),vectPost->end(),vectInorder->at(i))-vectPost->begin(); nca = nca>tempIndex?nca:tempIndex; } if(nca==-1) { return -1; } cout<<" The NCA of "<< n1 <<" and "<< n2<< " = "<at(nca)<at(nca); }

No comments:

Post a Comment