class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
def insert(root, val):
if root is None:
return Node(val)
if val < root.val:
left_child = insert(root.left, val)
root.left = left_child
left_child.parent = root
else:
right_child = insert(root.right, val)
root.right = right_child
right_child.parent = root
return root
def find_node(root, val):
if root is None or root.val == val:
return root
if val < root.val:
return find_node(root.left, val)
else:
return find_node(root.right, val)
def leftmost(node):
while node.left:
node = node.left
return node
def inorder_successor(node):
# If right child exists, successor is leftmost in right subtree
if node.right:
return leftmost(node.right)
# Else move up until node is left child of parent
curr = node
while curr.parent and curr == curr.parent.right:
curr = curr.parent
return curr.parent
# Driver code
root = None
for v in [20, 10, 30, 15, 40]:
root = insert(root, v)
node = find_node(root, 15)
succ = inorder_successor(node)
if succ:
print(f"Successor of {node.val} is {succ.val}")
else:
print(f"No successor for {node.val}")Check if node has right subtree to find successor there
return leftmost(node.right)
Successor is leftmost node in right subtree
while curr.parent and curr == curr.parent.right:
Move up until node is left child of its parent
Return the parent which is the successor