Leetcode 2331. Evaluate Boolean Binary Tree
You are given the root
of a full binary tree with the following properties:
0
or 1
, representing False
and True
respectively.2
or 3
:
2
represents the boolean OR operation.3
represents the boolean AND operation.Return the boolean result of the evaluation of the binary tree.
Example:
Input: root = [2,1,3,null,null,0,1]
Output: true
Explanation: The above diagram represents the binary tree:
2
/ \
1 3
/ \
0 1
The evaluation of this tree would be True OR (False AND True), which is True.
0
or 1
.To solve this problem, we will perform a post-order traversal of the tree. Post-order traversal is suitable because we need to evaluate the children before we can evaluate the parent. Here is a step-by-step plan:
2
for OR and 3
for AND), combine the results of the left and right subtrees using the corresponding boolean operation.#include <iostream>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
bool evaluateTree(TreeNode* root) {
// Base case for leaf node
if (root->left == nullptr && root->right == nullptr) {
return root->val == 1;
}
// Recursively evaluate left and right subtrees
bool leftVal = evaluateTree(root->left);
bool rightVal = evaluateTree(root->right);
// Perform the operation based on the value of the node
if (root->val == 2) {
return leftVal || rightVal;
} else { // root->val must be 3
return leftVal && rightVal;
}
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?