Skip to main content
LeetCode Prep
CHAPTER 10 Beginner

Trees and Binary Trees

Updated: May 18, 2026
5 min read

# CHAPTER 10

Trees and Binary Trees

1. Chapter Introduction

Arrays and Linked Lists are *linear* (1-dimensional) data structures. Trees are *hierarchical* (2-dimensional) data structures. They are used to represent file systems, HTML DOMs, and organizational charts. In coding interviews, Tree problems are the ultimate test of your understanding of Recursion. This chapter covers Tree terminology, Depth-First Search (DFS), and Breadth-First Search (BFS).

2. Anatomy of a Binary Tree

A Tree consists of Nodes connected by edges. A Binary Tree is a tree where every node has *at most* two children (left and right).
  • Root: The top node of the tree.
  • Leaf: A node with zero children (the bottom of the tree).
  • Depth: The number of edges from the root down to a specific node.
  • Height: The maximum depth of the tree.

*The Node Class:*

java
123456
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

3. Tree Traversal: Depth-First Search (DFS)

DFS plunges as deep as possible down one branch until it hits a leaf, then backtracks. It is naturally implemented using Recursion (which uses the Call Stack under the hood).

There are 3 ways to order a DFS traversal. Given a tree:

text
123
      1
     / \
    2   3
  1. 1. Pre-Order (Node, Left, Right): [1, 2, 3]. Visit the node first. Good for copying a tree.
  1. 2. In-Order (Left, Node, Right): [2, 1, 3]. Visits nodes left-to-right. (Crucial for Binary Search Trees).
  1. 3. Post-Order (Left, Right, Node): [2, 3, 1]. Visit children before the parent. Good for deleting a tree.

*Standard DFS Template (In-Order):*

python
1234567891011121314
def inOrderTraversal(root):
    res = []
    
    def dfs(node):
        if not node: # Base Case: We hit the bottom
            return
            
        dfs(node.left)    # Go Left
        res.append(node.val) # Process Node
        dfs(node.right)   # Go Right
        
    dfs(root)
    return res
# Time: O(N), Space: O(H) where H is the height of the tree (Call Stack)

4. Tree Traversal: Breadth-First Search (BFS)

BFS explores the tree *level-by-level*. It looks at the root, then all children at level 1, then all grandchildren at level 2. BFS is NOT recursive. It is implemented iteratively using a Queue (FIFO).

*Standard BFS Template (Level Order Traversal):*

python
12345678910111213141516171819202122232425
from collections import deque

def levelOrder(root):
    if not root: return []
    
    res = []
    queue = deque([root]) # 1. Initialize queue with root
    
    while queue:
        level_size = len(queue)
        current_level = []
        
        # 2. Process all nodes on the CURRENT level
        for _ in range(level_size):
            node = queue.popleft() # Dequeue
            current_level.append(node.val)
            
            # 3. Add children to queue for the NEXT level
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
            
        res.append(current_level)
        
    return res
# Time: O(N), Space: O(W) where W is the max width of the tree

5. Pattern 1: Maximum Depth of Binary Tree

*Prompt:* Find the height of the tree (LeetCode 104). *The Recursive Logic:* The max depth of any node is 1 + the max depth of its deepest subtree.
java
1234567891011
public int maxDepth(TreeNode root) {
    // Base case: An empty tree has depth 0
    if (root == null) return 0;
    
    // Recursive calls down left and right subtrees
    int leftDepth = maxDepth(root.left);
    int rightDepth = maxDepth(root.right);
    
    // The answer is 1 (current node) + the larger of the two subtrees
    return Math.max(leftDepth, rightDepth) + 1;
}

*Why this is beautiful:* You don't need to track the global state. You define the rule for a single node, and recursion applies it to the entire tree.

6. Pattern 2: Tree Equality / Symmetry

*Prompt:* Determine if two binary trees are identical (LeetCode 100). *Logic:* Two trees are identical if:
  1. 1. Both nodes are null (True).
  1. 2. One is null, the other isn't (False).
  1. 3. The values are different (False).
  1. 4. isSameTree(p.left, q.left) AND isSameTree(p.right, q.right) are both True.

7. Real-World Scenario: DOM Traversal

When JavaScript queries document.getElementById('header'), the browser runs a DFS/BFS traversal on the HTML DOM (Document Object Model) Tree to locate the specific HTML node.

8. Mini Project: Invert a Binary Tree

This is the problem famously asked to Max Howell (creator of Homebrew) at Google. *Prompt:* Invert a binary tree (swap every left and right child). *Logic:*
  1. 1. If root is null, return.
  1. 2. Swap root.left and root.right.
  1. 3. Recursively call invertTree(root.left) and invertTree(root.right).
  1. 4. Return root.

9. Common Mistakes

  • Forgetting the Base Case: Every recursive tree function MUST start with if not root: return .... If you forget this, the recursion will attempt to access null.left, throwing a NullPointerException.
  • Global Variables: Trying to maintain a global count variable outside the recursive function. Interviewers hate this. Learn to return values *up* the recursive call stack.

10. Best Practices

  • Time Complexity: Tree traversal is almost always O(N) Time because you must visit every node exactly once.
  • Space Complexity: Recursion is NOT O(1) Space. Every recursive call adds a frame to the system Call Stack. The space complexity is O(H), where H is the height of the tree. (In worst-case unbalanced trees, H = N).

11. Exercises

  1. 1. Trace the Post-Order traversal of a tree with Root 1, Left 2, Right 3.
  1. 2. In the BFS Queue template, why do we calculate levelsize = len(queue) before the inner for loop?

12. MCQs

Question 1

In a Binary Tree, what is the maximum number of children a single node can have?

Question 2

What is the fundamental difference between Depth-First Search (DFS) and Breadth-First Search (BFS)?

Question 3

How is Depth-First Search (DFS) typically implemented in code?

Question 4

What is an "In-Order" traversal sequence?

Question 5

How is Breadth-First Search (BFS) / Level-Order Traversal typically implemented?

Question 6

What is the Time Complexity of traversing an entire Binary Tree using DFS or BFS?

Question 7

What is the Space Complexity of a recursive DFS algorithm?

Question 8

What is the mandatory "Base Case" for almost all recursive Tree algorithms?

Question 9

When calculating the "Maximum Depth" of a binary tree recursively, what does the parent node return to its caller?

Question 10

In a BFS Queue implementation, why do we record levelsize = queue.length at the start of the while loop?

14. Interview Questions

  • Q: "Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level in a 2D array)." (LeetCode 102).

15. FAQs

  • Q: Which is better, DFS or BFS?
A: It depends. If you are looking for a node close to the root, BFS is faster. If you are looking for a node deep at the bottom, DFS uses less memory (queue size gets very wide in BFS on large trees).

16. Summary

Trees evaluate your mastery of recursion. Master the three DFS traversal orders (Pre, In, Post) and the recursive base case (if not root:). Understand that the system Call Stack is used to backtrack, resulting in O(H) Space complexity. For level-by-level problems, implement BFS iteratively using a Queue. Always write clean, self-contained recursive functions rather than relying on messy global variables.

17. Next Chapter Recommendation

Standard Binary Trees are useful for traversal, but they don't help us *search* for data quickly. In Chapter 11: Binary Search Trees and Heaps, we will explore Trees with strict mathematical sorting rules, unlocking O(log N) operations.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·