Leetcode 2331: Evaluate Boolean Binary Tree

grid47
grid47
Exploring patterns and algorithms
Mar 18, 2024 5 min read

You are given the root of a full binary tree. The leaf nodes hold boolean values: 0 (False) and 1 (True). The non-leaf nodes hold values 2 (OR) or 3 (AND). Your task is to evaluate the tree according to the logical operations and return the final boolean result of the root node.
Problem
Approach
Steps
Complexity
Input: You are given the root of a full binary tree. Each node has a value of 0 or 1 (leaf nodes), or 2 (OR) or 3 (AND) for non-leaf nodes.
Example: root = [3, 2, 1, null, null, 0, 1]
Constraints:
• 1 <= Number of nodes <= 1000
• Each node has either 0 or 2 children.
• Leaf nodes have value 0 or 1, non-leaf nodes have value 2 or 3.
Output: Return the boolean result of evaluating the root node of the tree.
Example: Output: true
Constraints:
• The output should be a boolean value (true or false).
Goal: Evaluate the binary tree using logical operations (AND/OR) and return the result at the root node.
Steps:
• Check if the current node is a leaf node. If so, return its value.
• If the current node is not a leaf, recursively evaluate the left and right children.
• If the node is an AND node (value 3), return the result of applying AND on the left and right children's evaluations.
• If the node is an OR node (value 2), return the result of applying OR on the left and right children's evaluations.
Goal: The constraints involve ensuring that the binary tree follows the structure of a full binary tree and that nodes hold values within the specified limits.
Steps:
• The number of nodes in the tree is in the range [1, 1000].
• Leaf nodes have a value of 0 or 1.
• Non-leaf nodes have a value of 2 or 3.
• Every node has either 0 or 2 children.
Assumptions:
• The tree is a full binary tree, meaning each non-leaf node has exactly two children.
• The leaf nodes' values are either 0 or 1, representing boolean False and True respectively.
• Non-leaf nodes' values are either 2 (for OR operation) or 3 (for AND operation).
Input: root = [3, 2, 1, null, null, 0, 1]
Explanation: The evaluation starts from the leaf nodes. The OR operation at the left child evaluates to 1, and the AND operation at the root results in true.

Input: root = [2, 0, 0]
Explanation: The OR operation at the root evaluates to false since both children are 0 (False).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus