Coding Test/LeetCode

[LeetCode] 2331. Evaluate Boolean Binary Tree c++

owls 2022. 9. 26. 21:43
728x90
  • 문제

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.

The evaluation of a node is as follows:

  • If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.
  • Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.

Return the boolean result of evaluating the root node.

full binary tree is a binary tree where each node has either 0 or 2 children.

leaf node is a node that has zero children.

 

맨 하위단 부터 현재 노드의 val은 or , and 연산식이고,  다음 left 와 right의 val로 연산을 수행한다.

  • 문제 해결
 bool evaluateTree(TreeNode* root) {
        switch(root->val){
            case 0:
            case 1:
                return root->val;
            case 2:{
                bool b = evaluateTree(root->left);
                bool b2 = evaluateTree(root->right);
                return b || b2;
            }
            default:{
                bool b = evaluateTree(root->left);
                bool b2 = evaluateTree(root->right);
                return b && b2;
            }
        }       
        return true;
    }

 

다른 방법

    bool evaluateTree(TreeNode* root) {
        if (!root->left and !root->right)   return root->val;
        int l = evaluateTree(root->left);
        int r = evaluateTree(root->right);
        return (root->val == 2) ? l or r : l and r;
    }
728x90