Binary Tree Inorder Traversal in Python

Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 14 views 0 copies

Python code

24 lines
Python 3.9+
class 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

stdout
[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

  1. Use an explicit stack for an iterative version to avoid recursion depth limits.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.