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 ["Leaf1", "Node1", "Leaf2", "Leaf3", "Node2", "Root"]
Output: ["Leaf1", "Node1", "Leaf2", "Leaf3", "Node2", "Root"]
Explanation: The postorder traversal visits the nodes in the correct order.
EDGE CASE
Input: Binary tree with only one node
Output: ["Root"]
Explanation: The single node is the root and is returned as the only element.
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 postorder traversal and collect the node values.
1) If the current node is None, return an empty list.
2) Recursively traverse the left subtree and collect its values.
3) Recursively traverse the right subtree and collect its values.
4) Add the current node's value after traversing both subtrees.
5) Return the concatenation of the left subtree values, right subtree values, and the current node's value.
⚠️ 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 survey_tree(root):
if root is None:
return []
# Perform postorder traversal: left, right, root
left_subtree = survey_tree(root.left)
right_subtree = survey_tree(root.right)
return left_subtree + right_subtree + [root.val]
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.