Unit 8 Session 1 Standard (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?
False
if the tree is empty or the flower is not found.HAPPY CASE
Input: Binary tree with flowers ["Rose", "Lily", "Daisy", "Orchid", "Lilac", "Dahlia"] and target "Lilac"
Output: True
Explanation: The flower "Lilac" exists in the tree.
EDGE CASE
Input: Binary tree with flowers ["Rose", "Lily", "Daisy", "Orchid", "Lilac", "Dahlia"] and target "Hibiscus"
Output: False
Explanation: The flower "Hibiscus" does not exist in the tree.
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 Search problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the tree recursively to search for the target flower, returning True
if found, False
otherwise.
1) If the current node is None, return False.
2) If the current node's value matches the target flower, return True.
3) Recursively search the left subtree for the target flower.
4) Recursively search the right subtree for the target flower.
5) Return True if the flower is found in either subtree, otherwise return False.
⚠️ Common Mistakes
True
as soon as the flower is found, leading to unnecessary computations.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 find_flower(root, flower):
if root is None:
return False
# If the current node matches the target flower, return True
if root.val == flower:
return True
# Recursively search in the left and right subtrees
return find_flower(root.left, flower) or find_flower(root.right, flower)
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 N
represents the number of nodes in the binary tree.
O(N)
because the algorithm may need to visit each node to determine if the flower is present.O(H)
where H
is the height of the tree, due to the recursive call stack.