Evaluate Boolean Binary Tree — LeetCode 2331 Python Solution

EasyTreeDepth-First SearchBinary Tree
Problem
#2331
Reading time
2 min

The problem

You are given the root of a full binary tree with the following properties: Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.

Example

Input
root = [2,1,3,null,null,0,1]
Output
true
Explanation
The above diagram illustrates the evaluation process.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def evaluateTree(self, root: Optional[TreeNode]) -> bool:
        if root.left is None:
            return bool(root.val)
        op = or_ if root.val == 2 else and_
        return op(self.evaluateTree(root.left), self.evaluateTree(root.right))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2331. Evaluate Boolean Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2331. Evaluate Boolean Binary Tree?
LeetCode 2331. Evaluate Boolean Binary Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 2331. Evaluate Boolean Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2331. Evaluate Boolean Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2331. Evaluate Boolean Binary Tree cover?
LeetCode 2331. Evaluate Boolean Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview