Finding Inorder Successor of a node in a BST:

Algorithm:

  1. If right subtree of a node is NOT NULL, return the MIN element from the right subtree
  2. If right subtree of a node is NULL, return the deepest ancestor of a node where it comes from the left.

For explanation visit: https://www.youtube.com/watch?v=5cPbNCrdotA

def inorder_succ(root,node):
    temp = None
    if node.right:
        temp = node.right
        while temp.left != None:
            temp = temp.left
        return temp

    #If right subtree is null
    currentNode = root
    ancestors = []
    while currentNode:
        if currentNode.data == node.data:
            return ancestors[-1]
        if currentNode.data > node.data:
            ancestors.append(currentNode.data)
            currentNode = currentNode.left
        else:
            currentNode = currentNode.right

results matching ""

    No results matching ""