简体   繁体   中英

Algorithm to find common ancestor of two nodes given

If two nodes and root of tree are give to me. How to find the common ancestor of two nodes?

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, ie, 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM