-
[LeetCode] 2331. Evaluate Boolean Binary Tree c++Coding Test/LeetCode 2022. 9. 26. 21:43728x90
- 문제
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.
A full binary tree is a binary tree where each node has either 0 or 2 children.
A 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'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 897. Increasing Order Search Tree c++ (0) 2022.09.27 [LeetCode] 617. Merge Two Binary Trees c++ (0) 2022.09.27 [LeetCode] 938. Range Sum of BST c++ (0) 2022.09.26 [LeetCode] 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree c++ (0) 2022.09.26 [LeetCode] 27. Remove Element c++ (0) 2022.09.15