-
Notifications
You must be signed in to change notification settings - Fork 265
Is Symmetric Tree
"Unit 9 Session 1 (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 15 mins
- 🛠️ Topics: Trees, Recursion
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?
- Do the values of the nodes have any constraints?
- No, they can be any integers.
- What should be returned if the root has only one child?
- Return False.
HAPPY CASE
Input: root = TreeNode(6, TreeNode(2), TreeNode(3))
Output: True
Explanation: The root value 6 is equal to the product of its children 2 and 3.
EDGE CASE
Input: root = TreeNode(6, TreeNode(2))
Output: False
Explanation: The root has only one child.
EDGE CASE
Input: root = TreeNode(6)
Output: False
Explanation: The root has no children.
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 problems, we want to consider the following approaches:
- Depth-First Search (DFS)
- Breadth-First Search (BFS)
- Recursive approaches
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Check if the root has two children and if the value of the root is equal to the product of the values of its two children.
1) If the root is None, return False.
2) If the root has no left or right child, return False.
3) If the root has both children, check if root value is equal to the product of its left and right child values.
4) Return the result of the check.
- Not handling the case when the tree has only one child.
- Not handling the case when the tree has no children.
Implement the code to solve the algorithm.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_root_equal_product_of_children(root):
if not root or not root.left or not root.right:
return False
return root.val == root.left.val * root.right.val
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
- Trace through your code with an input to check for the expected output
- Catch possible edge cases and off-by-one errors
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in the tree.
-
Time Complexity:
O(1)
because we only perform a constant number of operations. -
Space Complexity:
O(1)
because we do not use any additional space."