Binary Tree Preorder Traversal
LeetCode 144 · Easy · solution, intuition & step-by-step walkthrough
Node → left → right.
This is how I solved Binary Tree Preorder Traversal (LeetCode 144), 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
Pre-order visits the node before its children: node, then left subtree, then right subtree.
Approach
- 1
dfs(None) returns.
- 2
Record node.val, then dfs(left), 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
#root,left,right
res = []
def dfs(node):
if node==None:
return None
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return resBinary Tree Preorder Traversal — FAQ
What is the intuition behind Binary Tree Preorder Traversal?
Pre-order visits the node before its children: node, then left subtree, then right subtree.
How do you solve Binary Tree Preorder Traversal (LeetCode 144)?
1. dfs(None) returns. 2. Record node.val, then dfs(left), dfs(right).
What is the time and space complexity of Binary Tree Preorder Traversal?
Time: O(n). Space: O(h). (Accepted approach: Recursive DFS.)
What are common mistakes in Binary Tree Preorder Traversal?
Iteratively, push right before left so left is processed first.