Unit 9 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Can the tree be empty?
What should be returned if the tree has only one node?
HAPPY CASE
3 (root)
/ \
9 20
/ \
15 7
Input: root
Output: [[3], [9, 20], [15, 7]]
Explanation: The level order traversal of the tree is [[3], [9, 20], [15, 7]].
EDGE CASE
Input: None
Output: []
Explanation: The tree is empty, so return an empty list.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Tree problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a BFS approach to traverse the tree level by level. Use a queue to keep track of nodes to be explored, and a list of lists to store the node values for each level.
1) If the tree is empty, return an empty list.
2) Create an empty queue and an empty list to store the result.
3) Add the root to the queue.
4) While the queue is not empty:
a) Get the number of nodes at the current level.
b) Create a list to store the values of the current level nodes.
c) For each node at the current level:
i) Pop the node from the queue.
ii) Add its value to the current level list.
iii) Add the left and right children to the queue for the next level.
d) Add the current level list to the result list.
5) Return the result list.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
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 level_order(root):
if not root:
return []
result = []
queue = deque()
queue.append(root)
while queue:
level_size = len(queue)
level_nodes = []
for i in range(level_size):
node = queue.popleft()
level_nodes.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_nodes)
return result
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.