Binary Tree in Python
Learn Binary Trees in Python! A fun, beginner-friendly guide to building trees, inserting nodes, and exploring inorder, preorder, and postorder traversals.
Try it yourself
Run this code directly in your browser. Click "Open in full editor" to experiment further.
Click Run to see output
Or press Ctrl + Enter
How it works
Welcome to the branchy world of the binary tree python edition! ๐ณ A binary tree is a hierarchical structure where each node holds a value and points to at most two children โ a left and a right. That tiny rule unlocks file systems, database indexes, parsers, ML decision trees, and the DOM. Trees model relationships: parent/child, bigger/smaller, before/after.
They're foundational because almost every fast lookup structure is a tree in disguise. Once recursion on a tree clicks, recursion everywhere else clicks too. Let's grow some roots.
Anatomy of a Binary Tree
Here's a tiny tree:
50 <- root (depth 0)
/ \
30 70 <- internal nodes
/ \ / \
20 40 60 80 <- leaves50). Every tree has exactly one.30 is the parent of 20 and 40.20, 40, 60, 80).Binary Tree Types
Not all binary trees are created equal. The shape matters โ a lot.
Tree Traversals
A tree traversal is the order you visit nodes. Four flavors:
1. In-order (Left โ Root โ Right): on a BST, outputs values in sorted order.
2. Pre-order (Root โ Left โ Right): great for copying or serializing a tree.
3. Post-order (Left โ Right โ Root): use for safe deletion (free leaves first) and evaluating expression trees bottom-up.
4. Level-order / BFS: use a queue. Perfect for shortest path in an unweighted tree, tree height, or printing level by level.
Recursive vs Iterative Traversal
The code above uses a recursive tree approach because trees are recursive by nature. But Python's call stack caps around 1000 frames, so for deep trees switch to iteration:
list as a stack. Push the root, then loop: pop, visit, push right child, push left.collections.deque as a queue. Append children right, popleft to visit.Complexity Analysis
| Operation | Balanced BST | Unbalanced BST | Notes |
|---|---|---|---|
| Search | O(log n) | O(n) | Halving the search space each step |
| Insert | O(log n) | O(n) | Same path as search |
| Delete | O(log n) | O(n) | Plus successor lookup |
| Traversal (any) | O(n) | O(n) | You must visit every node |
| Space (recursion) | O(log n) | O(n) | Call stack depth = tree height |
| Space (storage) | O(n) | O(n) | One node per value |
The headline: a balanced tree is exponentially faster than an unbalanced one. Balance is not optional in production.
Common Pitfalls
node is None. Skip this and you'll meet AttributeError: 'NoneType' object has no attribute 'left' fast.node1 == node2 checks identity unless you implement __eq__. To compare contents, compare .value, not the node objects.[1, 2, 3, 4, 5] into a vanilla BST creates a degenerate spine โ O(log n) becomes O(n). Shuffle first, or use AVL/red-black.set crushes them.def inorder(node, result=[]) shares the list across calls. Use result=None and initialize inside.Real-World Uses
Binary trees and their cousins are everywhere:
DecisionTreeClassifier, random forests, XGBoost.When NOT to Use a Binary Tree
set or dict.list or array.heapq) โ it's a complete binary tree but the API is way simpler.Frequently Asked Questions
What's the difference between a binary tree and a BST? A binary tree is the shape โ at most two children per node. A BST adds the ordering rule: left < parent < right. All BSTs are binary trees; not all binary trees are BSTs.
Why use a tree instead of a list? Lists give you O(n) search. A balanced BST gives you O(log n) search, insert, and ordered traversal. For 1M items, that's ~20 comparisons vs ~1,000,000.
How do I balance a binary tree? Two options: (1) use a self-balancing variant (AVL or red-black) that rebalances via rotations, or (2) for static data, sort the input and recursively pick the middle element as the root.
What's the max depth of a binary tree with N nodes? Worst case (degenerate): N - 1. Best case (balanced): lfloor log_2 N rfloor.
Is Python's `heapq` a binary tree? Yes โ a complete binary tree (min-heap) stored in a flat list using index math (parent = (i-1)//2, children = 2i+1, 2i+2).
How do I serialize a tree? Pre-order traversal with explicit None markers ("50,30,20,#,#,40,#,#,70,#,#") is the simplest reversible format. Level-order also works.
Now run the code, mess with the numbers, and try writing the iterative versions yourself! ๐ฑ
Related examples
Fibonacci Sequence in Python
Learn how to code the famous Fibonacci Sequence in Python! A fun, beginner-friendly guide comparing recursion, loops (iteration), and clever memoization.
Bubble Sort in Python
Learn the Bubble Sort algorithm in Python! Step-by-step visual explanation with beginner-friendly, optimized Python code.