Unit 9 Session 1 (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?
design
is None
?
HAPPY CASE
Input: croquembouche = Puff("Vanilla", Puff("Chocolate", Puff("Vanilla"), Puff("Matcha")), Puff("Strawberry"))
Output: ['Vanilla', 'Chocolate', 'Strawberry', 'Vanilla', 'Matcha']
Explanation: The flavors are printed level by level, starting from the root.
Input: croquembouche = Puff("Chocolate")
Output: ['Chocolate']
Explanation: The tree has only one node, so return its flavor.
EDGE CASE
Input: croquembouche = None
Output: []
Explanation: The tree is empty, so return an empty list.
Input: croquembouche = Puff("Vanilla", Puff("Chocolate"), None)
Output: ['Vanilla', 'Chocolate']
Explanation: The tree has only two nodes, and the second node is on the left.
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 problems involving traversing binary trees in level order, we can consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
1) Initialize:
design
tree is empty, return an empty list.Pseudocode:
1) If `design` is `None`, return an empty list.
2) Initialize a queue with `design` as the first element and an empty result list.
3) While the queue is not empty:
a) Dequeue the first node in the queue.
b) Append the node's value to the result list.
c) If the node has a left child, enqueue it.
d) If the node has a right child, enqueue it.
4) Print the result list.
Implement the code to solve the algorithm.
class Puff:
def __init__(self, flavor, left=None, right=None):
self.val = flavor
self.left = left
self.right = right
def print_design(design):
if not design:
return []
queue = deque([design])
result = []
while queue:
node = queue.popleft()
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
print(result)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
croquembouche = Puff("Vanilla", Puff("Chocolate", Puff("Vanilla"), Puff("Matcha")), Puff("Strawberry"))
:
['Vanilla', 'Chocolate', 'Strawberry', 'Vanilla', 'Matcha']
.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in the tree.
O(N)
because each node in the tree must be visited once.O(N)
due to the queue storing nodes at each level during traversal.