A Binary Search Tree (BST) is a binary tree with one special rule: for every node, ALL left descendants are smaller and ALL right descendants are larger. 🌲
💡 Think of it like this: Imagine organizing books on a shelf. Pick any book — everything to its LEFT has a title that comes BEFORE it alphabetically, and everything to its RIGHT comes AFTER. That's a BST!
BST Operations:
💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥
⚠️ Worst case: If you insert sorted data (1, 2, 3, 4, 5...), the BST becomes a linked list and operations become O(n). This is why balanced BSTs (AVL, Red-Black) exist!
# In-order traversal of BST above:
# 1, 3, 4, 6, 7, 8, 10, 14 ← SORTED!
def inorder(node):
if not node:
return
inorder(node.left) # Visit left
print(node.val) # Visit node
inorder(node.right) # Visit right
inorder(root)
[1, 3, 4, 6, 7, 8, 10, 14]
search_bst(root, 6)
True
search_bst(root, 5)
False