Trees and Binary Trees
# 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:*
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:
-
1.
Pre-Order (Node, Left, Right):
[1, 2, 3]. Visit the node first. Good for copying a tree.
-
2.
In-Order (Left, Node, Right):
[2, 1, 3]. Visits nodes left-to-right. (Crucial for Binary Search Trees).
-
3.
Post-Order (Left, Right, Node):
[2, 3, 1]. Visit children before the parent. Good for deleting a tree.
*Standard DFS Template (In-Order):*
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):*
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 is1 + the max depth of its deepest subtree.
*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. Both nodes are null (True).
- 2. One is null, the other isn't (False).
- 3. The values are different (False).
-
4.
isSameTree(p.left, q.left)ANDisSameTree(p.right, q.right)are both True.
7. Real-World Scenario: DOM Traversal
When JavaScript queriesdocument.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. If root is null, return.
-
2.
Swap
root.leftandroot.right.
-
3.
Recursively call
invertTree(root.left)andinvertTree(root.right).
-
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 accessnull.left, throwing aNullPointerException.
-
Global Variables: Trying to maintain a global
countvariable 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. Trace the Post-Order traversal of a tree with Root 1, Left 2, Right 3.
-
2.
In the BFS Queue template, why do we calculate
levelsize = len(queue)before the innerforloop?
12. MCQs
In a Binary Tree, what is the maximum number of children a single node can have?
What is the fundamental difference between Depth-First Search (DFS) and Breadth-First Search (BFS)?
How is Depth-First Search (DFS) typically implemented in code?
What is an "In-Order" traversal sequence?
How is Breadth-First Search (BFS) / Level-Order Traversal typically implemented?
What is the Time Complexity of traversing an entire Binary Tree using DFS or BFS?
What is the Space Complexity of a recursive DFS algorithm?
What is the mandatory "Base Case" for almost all recursive Tree algorithms?
When calculating the "Maximum Depth" of a binary tree recursively, what does the parent node return to its caller?
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
rootof 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?
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.