Binary Tree Inorder Traversal
LeetCode 94 · Easy · solution, intuition & step-by-step walkthrough
Left → node → right.
This is how I solved Binary Tree Inorder Traversal (LeetCode 94), an easy problem from the Traversals (Recursive / Iterative) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
In-order means left subtree, then the node, then the right subtree. A recursive helper that follows that order appends values in sorted order for a BST.
Approach
- 1
dfs(None) returns.
- 2
dfs(left), record node.val, dfs(right).
How I solved it
Recursive DFSPythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
#left,root,right
res = []
def dfs(node):
if node==None:
return None
dfs(node.left)
res.append(node.val)
dfs(node.right)
dfs(root)
return resBinary Tree Inorder Traversal — FAQ
What is the intuition behind Binary Tree Inorder Traversal?
In-order means left subtree, then the node, then the right subtree. A recursive helper that follows that order appends values in sorted order for a BST.
How do you solve Binary Tree Inorder Traversal (LeetCode 94)?
1. dfs(None) returns. 2. dfs(left), record node.val, dfs(right).
What is the time and space complexity of Binary Tree Inorder Traversal?
Time: O(n). Space: O(h). (Accepted approach: Recursive DFS.)
What are common mistakes in Binary Tree Inorder Traversal?
An explicit stack avoids recursion limits on very deep trees.