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?
True
. If only one tree is empty, return False
.HAPPY CASE
Input:
root1 = TreeNode(1, TreeNode(2), TreeNode(3))
root2 = TreeNode(1, TreeNode(2), TreeNode(3))
Output: True
Explanation: The trees have identical structures and values.
EDGE CASE
Input:
root1 = TreeNode(1, TreeNode(2))
root2 = TreeNode(1, None, TreeNode(2))
Output: False
Explanation: The trees have different structures.
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 Comparison problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse both trees simultaneously. At each step, check if the nodes at the corresponding positions in both trees have the same value and that their subtrees are also identical.
1) If both nodes (root1 and root2) are None, return True.
2) If one of the nodes is None and the other is not, return False.
3) If the values of root1 and root2 are not equal, return False.
4) Recursively check if the left subtrees are identical.
5) Recursively check if the right subtrees are identical.
6) Return True if both the left and right subtrees are identical.
⚠️ 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 is_identical(root1, root2):
# Base Case
if root1 is None and root2 is None:
return True
if root1 is None or root2 is None:
return False
# Recursive Case
if root1.val == root2.val:
return is_identical(root1.left, root2.left) and is_identical(root1.right, root2.right)
return False
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:
root1 = TreeNode(1, TreeNode(2), TreeNode(3))
root2 = TreeNode(1, TreeNode(2), TreeNode(3))
Expected Output: True
root1 = TreeNode(1, TreeNode(2))
root2 = TreeNode(1, None, TreeNode(2))
Expected Output: False
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 trees.
O(N)
because the algorithm needs to visit each node in both trees.O(H)
where H
is the height of the trees, due to the recursive call stack.