Skip to content

2331. Evaluate Boolean Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  bool evaluateTree(TreeNode* root) {
    if (root->val < 2)
      return root->val;
    if (root->val == 2)  // OR
      return evaluateTree(root->left) || evaluateTree(root->right);
    // AND
    return evaluateTree(root->left) && evaluateTree(root->right);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public boolean evaluateTree(TreeNode root) {
    if (root.val < 2)
      return root.val == 1;
    if (root.val == 2) // OR
      return evaluateTree(root.left) || evaluateTree(root.right);
    // AND
    return evaluateTree(root.left) && evaluateTree(root.right);
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def evaluateTree(self, root: TreeNode | None) -> bool:
    if root.val < 2:
      return root.val
    if root.val == 2:  # OR
      return self.evaluateTree(root.left) or self.evaluateTree(root.right)
    # AND
    return self.evaluateTree(root.left) and self.evaluateTree(root.right)