We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Check if given data is present in given node or notboolsearch(Node*root,intdata){while(root!=nullptr){if(root->data==data){returntrue;}elseif(data<root->data){root=root->left;}else{root=root->right;}}returnfalse;}Node*lca(Node*root,intv1,intv2){stack<Node*>s;Node*temp=root;// searching for v1 and storing its path in stackwhile(temp!=nullptr){s.push(temp);if(temp->data==v1){break;}elseif(v1<temp->data){temp=temp->left;}else{temp=temp->right;}}// search complete// search for v2 in each ancestor of v1while(!s.empty()){if(search(s.top(),v2)){Node*ans=s.top();returnans;}s.pop();}returnnullptr;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Search Tree : Lowest Common Ancestor
You are viewing a single comment's thread. Return to all comments →
C++ solution