Problem
You are given the root of a full binary tree with the following properties:
- Leaf nodes have either the value
0or1, where0representsFalseand1representsTrue. - Non-leaf nodes have either the value
2or3, where2represents the booleanORand3represents the booleanAND.
The evaluation of a node is as follows:
- If the node is a leaf node, the evaluation is the value of the node, i.e.
TrueorFalse. - Otherwise, evaluate the node’s two children and apply the boolean operation of its value with the children’s evaluations.
Return the boolean result of evaluating the root node.
A full binary tree is a binary tree where each node has either 0 or 2 children.
A leaf node is a node that has zero children.
Examples
Example 1:
graph TD;
A(OR) --- B(True) & C(AND);
C --- D(False) & E(True)
Result in:
graph TD;
A(OR) --- B(True) & C(False);
Results in:
graph TD;
A(True)
| |
Example 2:
| |
Solution
Method 1 - Recursive DFS
We can perform postorder DFS.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)(assuming recursive stack is not counted,O(n)otherwise)