Welcome to Day 8 of your coding interview journey.
So far, youβve covered:
- β Day 1: HashMaps
- β Day 2: Sliding Window
- β Day 3: Arrays
- β Day 4: Two Pointers
- β Day 5: Interval Problems
- β Day 6: Binary Search
- β Day 7: Heaps
Today, we step into a core computer science topic:
π Trees (Binary Trees)
π§ What is a Binary Tree?
A Binary Tree is a structure where:
- Each node has at most 2 children
- Left child
- Right child
Example Structure:
3
/ \
9 20
/ \
15 7
π Why Trees Matter in Interviews
Trees test:
- Recursion
- Traversal techniques
- Data structure understanding
π³ Basic Tree Node in Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
π‘ Problem 1 β Maximum Depth of Binary Tree
π§© Problem
Given the root of a binary tree:
π Return its maximum depth
(The number of levels from root to the deepest leaf)
π§ Approach β Recursion (DFS)
π The depth of a node is:
1 + max(left_depth, right_depth)
π οΈ Solution in Python
def max_depth(root):
if not root:
return 0
left = max_depth(root.left)
right = max_depth(root.right)
return 1 + max(left, right)
β Example
For the tree:
3
/ \
9 20
/ \
15 7
Output:
3
β‘ Complexity
- Time:
O(n) - Space:
O(h)(height of tree)
π― Key Insight
π This is a classic Divide & Conquer (DFS) problem
π‘ Problem 2 β Binary Tree Level Order Traversal
π§© Problem
Return the level order traversal of a tree:
π Nodes level by level (left to right)
β Example Output
[[3], [9, 20], [15, 7]]
π§ Approach β Breadth-First Search (BFS)
π Use a queue to process nodes level by level
π οΈ Solution in Python
from collections import deque
def level_order(root):
if not root:
return []
result = []
queue = deque([root])
while queue:
level = []
size = len(queue)
for _ in range(size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
β‘ Complexity
- Time:
O(n) - Space:
O(n)
π― Key Insight
π BFS processes nodes level by level
This pattern is extremely common in tree problems.
β οΈ Common Mistakes
- β Confusing DFS vs BFS
- β Forgetting base case (
if not root) - β Not handling empty trees
- β Mismanaging queue size for levels
π§ͺ Practice Problems
To master trees, try:
- Same Tree
- Invert Binary Tree
- Diameter of Binary Tree
- Balanced Binary Tree
- Lowest Common Ancestor
π― Key Takeaways
- Trees rely heavily on:
- Recursion (DFS)
- Queues (BFS)
- Learn to identify:
- Depth problems β DFS
- Level problems β BFS
π Your Challenge (Day 8)
Solve this:
Invert a binary tree (swap left and right nodes).
π Final Thoughts
Trees are one of the most important topics in interviews.
Once youβre comfortable with:
- DFS
- BFS
Youβll be able to solve a huge range of problems.