Binary Tree Inorder Traversal in Python
Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.
Python code
24 linesclass TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) if root else []
if __name__ == "__main__":
# Build a sample tree: 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(inorder_traversal(root))
Output
[4, 2, 5, 1, 3]
How it works
The TreeNode class models each node with a value and left/right children, defaulting to None. The inorder_traversal function recursively visits the left subtree, appends the current node's value, then visits the right subtree. The base case returns an empty list for a None node, ensuring clean concatenation. Recursion naturally follows the LNR (left-node-right) order required for in-order traversal.
Common mistakes
- Forgetting the base case return [] when root is None, causing a TypeError.
- Placing the node value append in the wrong position, breaking the LNR order.
- Building the tree incorrectly by not linking left/right children properly.
Variations
- Use an explicit stack for an iterative version to avoid recursion depth limits.
- Collect nodes in a separate list parameter instead of concatenating lists.
Real-world use cases
- Displaying binary search tree keys in sorted order for reporting tools.
- Validating a binary search tree by checking in-order output is strictly increasing.
- Converting a tree to a flat sorted list for exporting data to another system.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
- Compute Derived Fields with @dataclass __post_init__ in Python easy
Keep learning
Related tutorials and quizzes for this topic.