Thursday, March 27, 2014

Write an algorithm to find the ‘next’ node (e.g., in-order successor) of a given node in a binary search tree where each node has a link to its parent.

__author__ = 'nitin'

def find_inorder_succ(node):
    if node is not None:
        if node.getRootVal() is None and node.getRightChild() is not None:
            p=left_most_child(node.getRightChild())
        else:
            p=node
            while p.getRootVal() is not None:
                if p.getLeftChild()==node:
                    break
                node=node.getRootVal()
                p=node
        return p
    return None

def left_most_child(node):
    if node is None:
        return None
    while node.getLeftChild() is not None:
        node=node.getLeftChild()
    return node

No comments:

My Profile

My photo
can be reached at 09916017317