If two nodes and root of tree are give to me. How to find the common ancestor of two nodes?
Asked
Active
Viewed 367 times
0
-
Possible duplicate of http://stackoverflow.com/questions/1484473/how-to-find-the-lowest-common-ancestor-of-two-nodes-in-any-binary-tree – lurker Aug 23 '13 at 12:42
-
see here: http://stackoverflow.com/questions/1484473/how-to-find-the-lowest-common-ancestor-of-two-nodes-in-any-binary-tree – fen Aug 23 '13 at 12:44
2 Answers
0
You can follow this approach
While traversing Binary Search Tree from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 < n < n2 is the Lowest or Least Common Ancestor(LCA) of n1 and n2 (where n1 < n2). So just traverse the BST in pre-order, if you find a node with value in between n1 and n2 then n is the LCA, if it's value is greater than both n1 and n2 then our LCA lies on left side of the node, if it's value is smaller than both n1 and n2 then LCA lies on right side.
Its a commonly asked programming question in interview you could have easily found its solution on interview sites

amod
- 4,190
- 10
- 49
- 75
0
Hi here's a python implementation that I found useful for LCA :-
class BST(object):
def __init__(self, val=None, right=None, left=None):
self.val = val
self.right = right
self.left = left
return None
def __nonzero__(self):
return self.val is not None
def insert(self, item):
if not self:
self.val = item
elif item < self.val:
if self.left:
return self.left.insert(item)
else:
self.left = BST(val=item)
elif item > self.val:
if self.right:
return self.right.insert(item)
else:
self.right = BST(val=item)
return None
def lca(self, m, n):
if n < self.val:
return self.left.lca(m, n)
elif m > self.val:
return self.right.lca(m, n)
else:
return self.val
if __name__ == "__main__":
b = BST()
for k in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
b.insert(k)
for pair in [(4, 7), (4, 10), (1, 4), (1, 3), (3, 6)]:
print b.lca(*pair)

aamir23
- 1,143
- 15
- 23