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 ["CoralA", "CoralB", "CoralD", "CoralE", "CoralC"]
Output: ["CoralA", "CoralB", "CoralD", "CoralE", "CoralC"]
Explanation: The preorder traversal visits the nodes in the correct order.
EDGE CASE
Input: Binary tree with only one node ["CoralA"]
Output: ["CoralA"]
Explanation: The tree only has a root, so the output is just the root's value.
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 Traversal problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the tree using preorder traversal and collect the node values.
1) If the current node is None, return an empty list.
2) Start by visiting the root node and store its value.
3) Recursively traverse the left subtree and collect its values.
4) Recursively traverse the right subtree and collect its values.
5) Return the list of node values from the traversal.
⚠️ 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 explore_reef(root):
# Base case: if the current node is None, return an empty list
if root is None:
return []
# Preorder traversal: visit root, left subtree, then right subtree
result = [root.val] # Visit the current node
result += explore_reef(root.left) # Traverse the left subtree
result += explore_reef(root.right) # Traverse the right subtree
return result
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 visits each node once.O(H)
where H
is the height of the tree, due to the recursive call stack.