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.
java 8 simplest solution
1. checking if both v1 & v2 less than current node then lca resides in left substree.
2. else if both v1 & v2 greater than current node then lca resides in right substree.
3. if not both previous then lca node is the node where v1 & v2 divide into different subtree or current node data is v1 or v2, so return this node.
Nodenode=root;while(node!=null){if(v1<node.data&&v2<node.data)node=node.left;elseif(v1>node.data&&v2>node.data)node=node.right;elsereturnnode;}returnnull;// if not found
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 →
java 8 simplest solution 1. checking if both v1 & v2 less than current node then lca resides in left substree. 2. else if both v1 & v2 greater than current node then lca resides in right substree. 3. if not both previous then lca node is the node where v1 & v2 divide into different subtree or current node data is v1 or v2, so return this node.