Unit 8 Session 1 Standard (Click for link to problem statements)
Unit 8 Session 1 Advanced (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?
HAPPY CASE
Input: Binary tree with nodes ["CaveA", "CaveB", "CaveD", "CaveE", "CaveC", "CaveF"]
Output: ["CaveA", "CaveB", "CaveD"]
Explanation: The leftmost path is ["CaveA", "CaveB", "CaveD"].
EDGE CASE
Input: Binary tree with nodes ["CaveA", "CaveB", "CaveC"] where only the root has children.
Output: ["CaveA"]
Explanation: The root has no left children, so the path only includes the root.
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 Path problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the tree starting from the root, following the left child at each step, and collect the values in a list.
1) Initialize an empty list to store the path.
2) While the current node is not None:
a) Add the current node's value to the path.
b) Move to the left child of the current node.
3) Return the path list after traversing.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class TreeNode:
def __init__(self, value, left=None, right=None):
self.val = value
self.left = left
self.right = right
def leftmost_path(root):
path = []
# Traverse the tree while there's a node
while root:
path.append(root.val) # Add the current node's value to the path
root = root.left # Move to the left child (if it exists)
return path
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.
Assume H
represents the height of the binary tree.
O(H)
because the algorithm only traverses the height of the tree.O(H)
because the path list stores up to H
elements, one for each level of the tree.