|
| 1 | +""" |
| 2 | +You are given the root of a full binary tree with the following properties: |
| 3 | +
|
| 4 | +Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. |
| 5 | +Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. |
| 6 | +The evaluation of a node is as follows: |
| 7 | +
|
| 8 | +If the node is a leaf node, the evaluation is the value of the node, i.e. True or False. |
| 9 | +Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations. |
| 10 | +Return the boolean result of evaluating the root node. |
| 11 | +
|
| 12 | +A full binary tree is a binary tree where each node has either 0 or 2 children. |
| 13 | +
|
| 14 | +A leaf node is a node that has zero children. |
| 15 | +
|
| 16 | +
|
| 17 | +
|
| 18 | +Example 1: |
| 19 | +
|
| 20 | +
|
| 21 | +Input: root = [2,1,3,null,null,0,1] |
| 22 | +Output: true |
| 23 | +Explanation: The above diagram illustrates the evaluation process. |
| 24 | +The AND node evaluates to False AND True = False. |
| 25 | +The OR node evaluates to True OR False = True. |
| 26 | +The root node evaluates to True, so we return true. |
| 27 | +Example 2: |
| 28 | +
|
| 29 | +Input: root = [0] |
| 30 | +Output: false |
| 31 | +Explanation: The root node is a leaf node and it evaluates to false, so we return false. |
| 32 | +
|
| 33 | +
|
| 34 | +Constraints: |
| 35 | +
|
| 36 | +The number of nodes in the tree is in the range [1, 1000]. |
| 37 | +0 <= Node.val <= 3 |
| 38 | +Every node has either 0 or 2 children. |
| 39 | +Leaf nodes have a value of 0 or 1. |
| 40 | +Non-leaf nodes have a value of 2 or 3. |
| 41 | +""" |
| 42 | + |
| 43 | + |
| 44 | +# Definition for a binary tree node. |
| 45 | +# class TreeNode: |
| 46 | +# def __init__(self, val=0, left=None, right=None): |
| 47 | +# self.val = val |
| 48 | +# self.left = left |
| 49 | +# self.right = right |
| 50 | +class Solution: |
| 51 | + def evaluateTree(self, root: Optional[TreeNode]) -> bool: |
| 52 | + if not root.left and not root.right: |
| 53 | + return 0 if root.val == 0 else 1 |
| 54 | + left = self.evaluateTree(root.left) |
| 55 | + right = self.evaluateTree(root.right) |
| 56 | + return left | right if root.val == 2 else left & right |
| 57 | + |
| 58 | + |
0 commit comments