Article start
DSA Course: Interview Patterns and Problem Solving
Module 6: Trees

Binary Tree Traversals: DFS recursion Pattern

Traverse a binary tree in left-root-right order using recursive DFS.

May 29, 2026·23

Learning Outcome

After this lesson, you should be able to explain inorder traversal and write a clean recursive DFS that visits every node once.

Problem Statement

Given the root of a binary tree, return the inorder traversal of its node values. Inorder means: visit left subtree, then current node, then right subtree.

InputOutputWhy
[1,null,2,3][1,3,2]Visit 1, then the left child of 2, then 2.

Brute Force Approach

Store root-to-node paths or flatten the tree with a less precise traversal, then try to reorder values later.

This makes the problem harder than needed. Traversal order should be produced directly while visiting the tree.

Optimized Approach

Use DFS recursion. For each node, recursively process the left child, add the current value, then recursively process the right child.

Exact Pseudocode

answer = []
dfs(node):
  if node is null:
    return
  dfs(node.left)
  answer.add(node.val)
  dfs(node.right)
dfs(root)
return answer

Reference Code

class Solution:
    def inorderTraversal(self, root):
        answer = []

        def dfs(node):
            if not node:
                return
            dfs(node.left)
            answer.append(node.val)
            dfs(node.right)

        dfs(root)
        return answer

Sample Dry Run

NodeActionanswer
1Left is null, add 1[1]
2Go left to 3 before adding 2[1]
3Add 3[1,3]
2Add 2 after left subtree[1,3,2]

Complexity

MeasureValueReason
TimeO(n)Every node is visited once.
SpaceO(h)The recursion stack depends on tree height.

Edge Cases

  • Empty tree returns an empty list.
  • Single-node tree returns that one value.
  • Skewed tree may have recursion depth O(n).

Interview Checklist

  • Remember inorder is left, root, right.
  • Add the value between left and right recursion.
  • State recursion stack space separately from output space.

FAQs

What is inorder traversal?

It visits the left subtree, then the node, then the right subtree.

Why is recursion natural for trees?

Each subtree is itself a tree, so the same function can solve the same problem on smaller roots.

What is the core pattern?

Recursive DFS traversal.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.