Validate BST, search/insert/delete, and transform BSTs
BST invariant (left < root < right) enables ordered traversal, rank queries, and structural updates.
Use when order-based queries/updates are needed with tree structure.
Bounded DFS validation using min/max ranges and standard BST search/insert/delete leveraging the BST ordering invariant.
# BST Templates
def is_valid_bst(root):
def dfs(n, lo, hi):
if not n: return True
if not (lo < n.val < hi): return False
return dfs(n.left, lo, n.val) and dfs(n.right, n.val, hi)
return dfs(root, float('-inf'), float('inf'))
def bst_search(root, key):
cur=root
while cur:
if key==cur.val: return cur
cur = cur.left if key<cur.val else cur.right
return NoneCheck bounds during DFS
def is_valid_bst(root):
def dfs(node, lo, hi):
if not node: return True
if not (lo < node.val < hi): return False
return dfs(node.left, lo, node.val) and dfs(node.right, node.val, hi)
return dfs(root, float('-inf'), float('inf'))Inorder traversal counting nodes
def kth_smallest(root, k):
st=[]; node=root
while st or node:
while node: st.append(node); node=node.left
node=st.pop(); k-=1
if k==0: return node.val
node=node.rightRecursive updates preserving BST
def bst_insert(root, val):
if not root: return TreeNode(val)
if val < root.val: root.left = bst_insert(root.left, val)
elif val > root.val: root.right = bst_insert(root.right, val)
return root
def bst_delete(root, key):
if not root: return None
if key < root.val: root.left = bst_delete(root.left, key)
elif key > root.val: root.right = bst_delete(root.right, key)
else:
if not root.left: return root.right
if not root.right: return root.left
# replace with successor
s = root.right
while s.left: s = s.left
root.val = s.val
root.right = bst_delete(root.right, s.val)
return rootGreater sum tree/morph operations
def convert_bst(root):
acc = 0
def dfs(node):
nonlocal acc
if not node: return
dfs(node.right)
acc += node.val; node.val = acc
dfs(node.left)
dfs(root); return rootOperations cost proportional to height.
Recursion/stack depth = height.