-
Notifications
You must be signed in to change notification settings - Fork 254
Find Leftmost Path I
Unit 8 Session 1 (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Trees, Binary Trees, Path Finding
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?
- Question: What should the function return if the tree is empty?
- Answer: Return an empty list as there are no nodes to form a path.
HAPPY CASE
Input: TreeNode('a', TreeNode('b', TreeNode('d'), TreeNode('e')), TreeNode('c'))
Output: ['a', 'b', 'd']
Explanation: The leftmost path from the root leads to 'd'.
EDGE CASE
Input: TreeNode('a')
Output: ['a']
Explanation: The tree has only one node, so the leftmost path includes just the root node.
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.
This problem fits into tree traversal categories, specifically finding a path in a tree. The solution requires navigating through the tree from the root to the leftmost leaf, similar to depth-first search techniques.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the tree from the root, always choosing the left child until reaching the leftmost node.
1) Start with the root node.
2) Continue to traverse leftward and collect nodes until a node without a left child is reached.
3) Return the collected list of node values.
- Forgetting to handle the case where the tree or part of its structure is missing, which would lead to incorrect path calculation.
Implement the code to solve the algorithm.
def left_path(root):
"""
Recursively collects the values from the leftmost path of the binary tree starting from the given node.
Returns a list of the collected values.
"""
if root is None:
return []
path = [root.val]
while root.left:
root = root.left
path.append(root.val)
return path
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
- Validate the code with trees of varying depths and configurations to ensure all possible paths are correctly identified and collected.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
-
Time Complexity:
O(n)
in the worst case where n is the number of nodes along the leftmost path. This assumes a skewed tree leaning to the left. -
Space Complexity:
O(1)
as it primarily collects nodes along a single path without additional overhead.