Introduction
Imagine you have a collection of numbers and you want to keep them organized so you can find any number quickly. The problem is how to add a new number into this collection without losing the order that helps you find numbers fast.
Imagine a librarian placing new books on a shelf sorted by title. To add a new book, the librarian starts at the beginning and moves left or right depending on whether the new title comes before or after the current book, until finding the right empty spot to place it.
┌─────┐
│ 10 │
├─────┤
│ │
└─┬─┬─┘
│ │
┌───┘ └───┐
│ │
┌─┴─┐ ┌─┴─┐
│ 5 │ │ 15│
└───┘ └───┘
Insert 12:
Start at 10 → 12 > 10, go right
At 15 → 12 < 15, go left (empty)
Place 12 here.class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) return current = self.root while True: if value < current.value: if current.left is None: current.left = Node(value) return current = current.left else: if current.right is None: current.right = Node(value) return current = current.right def inorder(self, node, result): if node: self.inorder(node.left, result) result.append(node.value) self.inorder(node.right, result) bst = BST() bst.insert(10) bst.insert(5) bst.insert(15) bst.insert(12) result = [] bst.inorder(bst.root, result) print(result)