Unit 8 Session 1 Standard (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
or False
), while non-leaf nodes can have string values (AND
or OR
).HAPPY CASE
Input: Binary tree with root "OR" and children "True", "False"
Output: True
Explanation: The evaluation of "OR" with "True" and "False" is `True`.
EDGE CASE
Input: Binary tree with root "False" and no children
Output: False
Explanation: The root is a leaf node with value `False`, so it directly returns `False`.
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 Evaluation problems, we want to consider the following approaches:
AND
or OR
) on the child nodes.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Evaluate the boolean expression represented by the binary tree by applying the operation in each non-leaf node to its children.
1) If the root has no children, return its boolean value.
2) If the root has the value "AND", return the logical AND of the evaluations of its left and right children.
3) If the root has the value "OR", return the logical OR of the evaluations of its left and right children.
4) The result of the evaluation is returned as the final decision.
⚠️ Common Mistakes
AND
and OR
operations, leading to incorrect evaluations.Implement the code to solve the algorithm.
class TreeNode:
def __init__(self, value, right=None, left=None):
self.val = value
self.right = right
self.left = left
def get_decision(root):
# If root node has no children
if root.left is None and root.right is None:
return root.val
# Otherwise, apply the operation based on the current node's value
if root.val == "AND":
return root.left.val and root.right.val
elif root.val == "OR":
return root.left.val or root.right.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(1)
because the tree has at most three nodes, leading to constant-time evaluation.O(1)
as no additional space is used beyond the input.