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 printed 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: [Nothing]
Explanation: The tree is empty, so nothing will print.
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 print the node values as they are visited.
1) If the tree is empty, return None.
2) Create an empty queue and add the root node.
3) While the queue is not empty:
a) Pop the next node from the queue.
b) Print the node's value.
c) Add the left child to the queue if it exists.
d) Add the right child to the queue if it exists.
⚠️ 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 print_by_level(root):
# if the tree is empty
if root is None:
return None
# create a new empty queue
queue = deque()
# append the root of the tree to the queue
queue.append(root)
# while there are still nodes to explore
while queue:
# pop next node off the queue
current_node = queue.popleft()
# Print the node's value
print(current_node.val)
# if the current node has a left child
if current_node.left is not None:
# add the left child to the queue
queue.append(current_node.left)
# if the current node has a right child
if current_node.right is not None:
# add the right child to the queue
queue.append(current_node.right)
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.