Trees: DFS and BFS
Traverse a binary tree depth-first with recursion and breadth-first with a queue.
26 min
A tree is nodes connected without loops. In a binary tree each node has at most two children, left and right.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = rightTerms to know: the top node is the root, a node with no children is a leaf, the depth of a tree is the number of nodes on its longest root-to-leaf path.
Go as deep as possible, then back up. Recursion matches the shape of a tree perfectly: the answer for a node is built from the answers for its children.
def max_depth(node):
if node is None: # base case: an empty tree has depth 0
return 0
return 1 + max(max_depth(node.left), max_depth(node.right))Every recursive tree function has the same three parts: a base case (None), the recursive calls on left and right, and a step that combines their results. Time O(n), because each node is visited once. Space O(h), where h is the height (the call stack).
The three DFS orders differ only in when you handle the node: preorder (node, left, right), inorder (left, node, right: for a binary search tree this gives sorted order), postorder (left, right, node).
Visit the tree level by level, using a queue:
from collections import deque
queue = deque([root])
while queue:
for _ in range(len(queue)): # exactly one level per outer round
node = queue.popleft()
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)The for _ in range(len(queue)) trick processes one whole level at a time, which is what "level sums", "right-side view" and "minimum depth" need.
Use DFS (recursion) for anything where a node's answer depends on its subtrees: depth, balance, path sums. Use BFS for anything level-based, or "closest to the root first".
The tree [3, 9, 20, None, None, 15, 7]: depth 3, level sums 3, 29 and 22.
Write max_depth(root): the number of nodes on the longest path from the root down to a leaf. An empty tree is 0. Use recursion. The helper build_tree makes a tree from a level-order list, where None marks a missing child; leave it as it is.
max_depth(build_tree([3, 9, 20, None, None, 15, 7])) is 3.
Your code must satisfy
- max_depth(build_tree([3, 9, 20, None, None, 15, 7]))→3example
- max_depth(build_tree([]))→0empty
- max_depth(build_tree([1]))→1single
- max_depth(build_tree([1, 2, None, 3]))→3left chain
- max_depth(build_tree([1, 2, 3, 4, 5, 6, 7]))→3complete
- max_depth(build_tree([1, None, 2, None, 3]))→3lopsided
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(values):
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = [root]
i = 1
while queue and i < len(values):
node = queue.pop(0)
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
def max_depth(root):
passWrite level_sums(root): a list holding the sum of the values on each level, from the root down. An empty tree gives []. Use a queue (breadth-first). build_tree is given.
level_sums(build_tree([3, 9, 20, None, None, 15, 7])) is [3, 29, 22].
Your code must satisfy
- level_sums(build_tree([3, 9, 20, None, None, 15, 7]))→[3,29,22]example
- level_sums(build_tree([]))→[]empty
- level_sums(build_tree([5]))→[5]single
- level_sums(build_tree([1, 2, 3, 4, 5, 6, 7]))→[1,5,22]complete
- level_sums(build_tree([1, -2, -3]))→[1,-5]negative values
- level_sums(build_tree([1, 2, None, 3]))→[1,2,3]left chain
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(values):
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = [root]
i = 1
while queue and i < len(values):
node = queue.pop(0)
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
def level_sums(root):
pass“Recursion on a tree means tracing every call in my head.”
For a loop you can follow every step, so you try the same here.
What is actually true
Trust the recursion: assume the function already works for the left and right subtrees, and only decide what to do at this node. Check the base case and the combining step, and the rest follows.
How to catch yourself
Write the base case first, then ask: "if I had the answers for both children, what is mine?"
Which traversal when.
DFS (recursion)
- Uses
- call stack
- Space
- O(h), the height
- Best for
- depth, balance, path sums, anything built from subtrees
Best for answers made of the children's answers
BFS (queue)
- Uses
- deque
- Space
- O(w), the widest level
- Best for
- level sums, shortest path in steps, right-side view
Best for level by level
- A binary tree node has
val,leftandright;Nonemarks no child. - DFS with recursion: base case on
None, recurse on both children, combine the results. - BFS uses a queue; freeze
len(queue)to process one level per round. - Both visit every node once: O(n) time.
Tree checks.
What is max_depth of an empty tree?
- A-1
- B0
- C1
- DNone
Which structure drives breadth-first search?
- AStack
- BQueue
- CSet
- DHeap
How many nodes does a full binary tree with 3 levels have?
Which order gives sorted values on a binary search tree?
- APreorder
- BInorder
- CPostorder
- DLevel order
Put the three parts of a recursive tree function in order.
- ARecurse on left and right
- BBase case: return for None
- CCombine the children's results
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.