LeetCode 2331: Evaluate Boolean Binary Tree Solution

Master LeetCode problem 2331 (Evaluate Boolean Binary Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2331. Evaluate Boolean Binary Tree

Problem Explanation

Explanation:

To evaluate the boolean binary tree, we need to recursively traverse the tree and perform the appropriate boolean operation based on the node's value. We can start by defining a recursive function that takes a node as input and returns the evaluation result. If the node is a leaf node, we return its boolean value (0 for False, 1 for True). Otherwise, we recursively evaluate the left and right children and apply the boolean operation based on the node's value (2 for OR, 3 for AND).

Algorithm:

  1. Define a recursive function evaluateNode that takes a node as input.
  2. If the node is a leaf node, return its boolean value.
  3. Recursively evaluate the left and right children using the evaluateNode function.
  4. Apply the boolean operation based on the node's value.
  5. Return the result.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree.

Space Complexity:

The space complexity of this algorithm is O(h), where h is the height of the binary tree.

:

Solution Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public boolean evaluateBoolTree(TreeNode root) {
    if (root == null) return true;
    
    return evaluateNode(root) == 1;
}

private int evaluateNode(TreeNode node) {
    if (node == null) return 1; // default to True
    
    if (node.left == null && node.right == null) {
        return node.val;
    }
    
    int leftVal = evaluateNode(node.left);
    int rightVal = evaluateNode(node.right);
    
    if (node.val == 2) {
        return leftVal | rightVal;
    } else {
        return leftVal & rightVal;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2331 (Evaluate Boolean Binary Tree)?

This page provides optimized solutions for LeetCode problem 2331 (Evaluate Boolean Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2331 (Evaluate Boolean Binary Tree)?

The time complexity for LeetCode 2331 (Evaluate Boolean Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2331 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2331 in Java, C++, or Python.

Back to LeetCode Solutions