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.
Binary Search Tree : Lowest Common Ancestor
Binary Search Tree : Lowest Common Ancestor
Sort by
recency
|
763 Discussions
|
Please Login in order to post a comment
class Node: def init(self,info): self.info = info
self.left = None
self.right = None
'''
def lca(root, v1, v2): node=root if node is None: return None if node.info>v1 and node.info>v2: return lca(node.left,v1,v2) elif node.info
Oddly enough, my solution implemented the same way in Python as in Java failed test cases 2 and 7 only with Python
Solution with commented explanation.
public static Node lca(Node root, int v1, int v2) { // Write your code here. return recLca(root, v1, v2); } public static Node recLca(Node root, int v1, int v2) { if (root == null) { return null; } if (root.data == v1 || root.data == v2) { return root; } Node leftFind = recLca(root.left, v1, v2); Node rightFind = recLca(root.right, v1, v2); if (leftFind == null || rightFind == null) { return leftFind == null ? rightFind : leftFind; } if (leftFind.data == rightFind.data) { return leftFind; } else{ return root; } }