class Node: def __init__(self, val): self.val = val self.left = None self.right = None def inorder_successor(root, p): successor = None while root: if p.val < root.val: successor = root root = root.left else: root = root.right return successor.val if successor else None # Construct BST root = Node(20) root.left = Node(10) root.right = Node(30) root.left.left = Node(5) root.left.right = Node(15) root.left.right.left = Node(13) root.left.right.right = Node(17) p = root.left.right # Node with value 15 print(inorder_successor(root, p))
The inorder successor of node 15 is the smallest node in its right subtree, which is 17.
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def inorder_successor(root, p): successor = None while root: if p.val < root.val: successor = root root = root.left else: root = root.right return successor.val if successor else None # Construct BST root = Node(20) root.left = Node(10) root.right = Node(30) root.left.left = Node(5) root.left.right = Node(15) root.left.right.left = Node(13) root.left.right.right = Node(17) p = root.left.right.right # Node with value 17 print(inorder_successor(root, p))
Node 17 has no right child, so the successor is the lowest ancestor whose left child is also an ancestor of 17, which is 20.
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def inorder_successor(root, p): if p.right: curr = p.right while curr.left: curr = curr.left return curr.val successor = None while root: if p.val < root.val: successor = root root = root.left else: root = root.right return successor.val root = Node(20) root.left = Node(10) root.right = Node(30) root.left.left = Node(5) root.left.right = Node(15) p = root.right # Node with value 30 print(inorder_successor(root, p))
If the node has no right subtree and no successor found, successor remains None, so accessing successor.val raises an AttributeError.
The inorder successor is the next node visited after p in inorder traversal. If p has a right child, it's the leftmost node in that subtree. Otherwise, move up using parent pointers until you find a node that is a left child of its parent; that parent is the successor.
Only node 40 has no inorder successor because it is the largest node in the BST.
