Python - Tree traversal question
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
A tree traversal question is usually asking two things: what order should nodes be visited, and how should that order be implemented. In Python, the answer depends on the task. Depth-first traversals are natural for recursive structure, while breadth-first traversal is better when levels matter.
Start With a Simple Tree Model
A binary tree node can be represented with a small class. That is enough to demonstrate the common traversal orders.
Example tree:
This gives a tree where 1 is the root, 2 and 3 are its children, and the lower nodes form the remaining branches.
Depth-First Traversal Orders
Depth-first traversal visits one branch as far as possible before backtracking. The three common variants differ only in when the current node is processed.
For the sample tree, the outputs are:
- preorder:
1, 2, 4, 5, 3, 6 - inorder:
4, 2, 5, 1, 3, 6 - postorder:
4, 5, 2, 6, 3, 1
Inorder is especially important for binary search trees because it yields sorted values.
Breadth-First or Level-Order Traversal
If the question is about visiting nodes one level at a time, use breadth-first traversal with a queue.
For the same tree, level order produces 1, 2, 3, 4, 5, 6.
Recursive vs Iterative Solutions
Many Python answers use recursion because the code matches the tree structure and is easy to read. That is fine for interviews, teaching, and moderate tree depth.
For very deep trees, iterative solutions can be safer because Python recursion has a depth limit. An iterative preorder traversal uses an explicit stack.
The stack pushes the right child first so the left child is processed first on the next loop iteration.
How To Choose the Right Traversal
Use preorder when you need to process a node before its descendants, such as serializing a tree structure. Use inorder when tree ordering matters, especially in a binary search tree. Use postorder when children must be handled before parents, such as deleting a tree or computing bottom-up values. Use level order when the problem talks about distance from the root, shortest unweighted path by levels, or printing the tree one row at a time.
A lot of tree traversal questions become easy once you translate the problem statement into one of those four access patterns.
Common Pitfalls
The most common bug is forgetting the base case for None, which causes attribute errors when the traversal reaches a missing child.
Another issue is using recursion on a very deep tree and hitting Python's recursion limit. If the tree can be highly unbalanced, prefer an iterative approach.
Developers also sometimes choose inorder on a tree that is not a binary search tree and then expect sorted output. Inorder only gives sorted values when the tree already satisfies binary search tree ordering.
Finally, be clear about whether the question wants a list of visited values, a generator, printed output, or some aggregated result. Those are different interfaces even if the traversal order is the same.
Summary
- Tree traversal means visiting nodes in a defined order.
- The main orders are preorder, inorder, postorder, and level order.
- Recursive implementations are concise, but iterative ones avoid recursion-depth problems.
- Pick the traversal based on when the current node should be processed.
- Clarify the required output before writing the traversal function.
Related reading
- Python and OpenCV - Improving my lane detection algorithm
- Python Brute Force algorithm
- Python CMA-ES Algorithm to solve user-defined function and constraints
- Python data structure sort list alphabetically
- Python 3 turn range to a list
- Python add item to the tuple
- Python - TypeError Object of type 'int64' is not JSON serializable
- python - TypeError unorderable types str float

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.