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 ["Shark", "Grouper", "Snapper", "Conch", "Tang", "Zooplankton"]
Output: 6
Explanation: There are 6 species in the food chain.
EDGE CASE
Input: Binary tree with only one node ["Shark"]
Output: 1
Explanation: The tree has only the root, so the count is 1.
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 Counting problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the tree recursively, counting each node.
1) If the current node is None, return 0.
2) Recursively count the nodes in the left subtree.
3) Recursively count the nodes in the right subtree.
4) Add 1 (for the current node) to the counts from the left and right subtrees.
5) Return the total count.
⚠️ 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 count_species(node):
if node is None:
return 0
# Recursively count the nodes in the left and right subtrees
left_count = count_species(node.left)
right_count = count_species(node.right)
# Add 1 for the current node
return 1 + left_count + right_count
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Test with the examples given:
- Input 1: Binary tree with nodes ["Shark", "Grouper", "Snapper", "Conch", "Tang", "Zooplankton"]
- Expected Output: 6
- Input 2: Binary tree with only one node ["Shark"]
- Expected Output: 1
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 needs to visit each node in the tree.O(H)
where H
is the height of the tree, due to the recursive call stack.