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?
door
tree is None
?
0
since there are no paths in the tree.1
since the root node is also the leaf node, making the minimum depth 1.HAPPY CASE
Input: door = Room("Door", Room("Attic"), Room("Cursed Room", Room("Crypt"), Room("Haunted Cellar")))
Output: 2
Explanation: The shortest path is from "Door" -> "Attic".
Input: door = Room("Door")
Output: 1
Explanation: The tree has only one node, so the minimum depth is 1.
EDGE CASE
Input: door = None
Output: 0
Explanation: The tree is empty, so return 0.
Input: door = Room("Door", Room("Attic"), None)
Output: 2
Explanation: The shortest path is from "Door" -> "Attic".
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 finding the minimum depth of a binary tree, we can consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
If you used a BFS approach, check out Minimum Depth of Secret Path II.
1) Base Case:
door
tree is None
, return 0
.1
.
2) Recursive Check:Pseudocode:
1) Define the base cases:
* If `door` is `None`, return `0`.
* If the current node is a leaf, return `1`.
2) Recursively calculate the depth of the left subtree (`left_depth = min_depth(door.left)`).
3) Recursively calculate the depth of the right subtree (`right_depth = min_depth(door.right)`).
4) Return `1 + min(left_depth, right_depth)` as the minimum depth.
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 min_depth(door):
if not door:
return 0
if not door.left and not door.right:
return 1
if not door.left:
return 1 + min_depth(door.right)
if not door.right:
return 1 + min_depth(door.left)
return 1 + min(min_depth(door.left), min_depth(door.right))
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
door = Room("Door", Room("Attic"), Room("Cursed Room", Room("Crypt"), Room("Haunted Cellar")))
:
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 recursive call stack in the worst case, assuming a balanced tree.