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.
c++14 : works for any binary tree (the first example was misleading: i thought we were not dealing with a bst)
booltrail(Node*root,constint&v,conststring&curpath,string&res){if(root->data==v){res=curpath;returntrue;}elseif(root->left&&root->right)returntrail(root->left,v,curpath+'0',res)||trail(root->right,v,curpath+'1',res);elseif(root->left)returntrail(root->left,v,curpath+'0',res);elseif(root->right)returntrail(root->right,v,curpath+'1',res);elsereturnfalse;}Node*traverse(Node*root,conststring&path){for(constauto&c:path){if(c=='0')root=root->left;elseroot=root->right;}returnroot;}stringgreatestcommonsubstr(conststring&s1,conststring&s2){stringres="";for(inti=0;i<s1.size();i++){if(s1[i]!=s2[i])break;res+=s1[i];}returnres;}Node*lca(Node*root,intv1,intv2){// Write your code here.stringpv1;stringpv2;trail(root,v1,"",pv1);trail(root,v2,"",pv2);root=traverse(root,greatestcommonsubstr(pv1,pv2));returnroot;}
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++14 : works for any binary tree (the first example was misleading: i thought we were not dealing with a bst)