Evaluate Boolean Binary Tree

To evaluate the tree, we’ll implement a depth-first search (DFS) and process the logic for each node accordingly.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def evaluateTree(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return False

        if not root.left and not root.right:  # if the node is a leaf
            return bool(root.val)

        left_val = self.evaluateTree(root.left)  # evaluate left child
        right_val = self.evaluateTree(root.right)  # evaluate right child

        if root.val == 2:  # OR operation
            return left_val or right_val
        else:  # AND operation
            return left_val and right_val

This code works by checking if the current node is a leaf. If it is, it returns the boolean value of the node. If it isn’t, it evaluates the left and right children. Then, it performs the operation specified by the node’s value on the evaluations of the children. The function does this recursively until all nodes in the tree have been evaluated.