What is Binary Search Tree
A binary search tree keeps every value in the left subtree smaller than the node, and every value in the right subtree larger. Search, insert, and the later queries all follow that rule.
insert 5 3 7 query 3 → 1 query 8 → 0
Approach
Start at the root. If the value is smaller, go left. If it is larger, go right. Insert creates a node only when the walk falls off the tree. Duplicates are skipped.
The picture inserts the values one at a time, then searches the query values. The practice output is 1 or 0 for each query.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Search or insert | O(h) | Each comparison moves one level down. |
| Build | O(n h) | n inserts. A sorted insert order makes a spine, so h can be n. |
Implementation
def insert(node, val):
if not node:
return TreeNode(val)
if val < node.val:
node.left = insert(node.left, val)
elif val > node.val:
node.right = insert(node.right, val)
return node
def search(node, val):
while node:
if val == node.val: return True
node = node.left if val < node.val else node.right
return False