You are given the root of a binary tree with the following properties:
Leaf nodes have either the value 0 or 1, representing false and true respectively.
Non-leaf nodes have either the value 2, 3, 4, or 5, representing the boolean operations OR, AND, XOR, and NOT, respectively.
You are also given a boolean result, which is the desired result of the evaluation of the root node.
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 children and apply the boolean operation of its value with the children's evaluations.
In one operation, you can flip a leaf node, which causes a false node to become true, and a true node to become false.
Return the minimum number of operations that need to be performed such that the evaluation of root yields result. It can be shown that there is always a way to achieve result.
A leaf node is a node that has zero children.
Note: NOT nodes have either a left child or a right child, but other non-leaf nodes have both a left child and a right child.
Example 1:
Input: root = [3,5,4,2,null,1,1,1,0], result = true
Output: 2
Explanation:
It can be shown that a minimum of 2 nodes have to be flipped to make the root of the tree
evaluate to true. One way to achieve this is shown in the diagram above.
Example 2:
Input: root = [0], result = false
Output: 0
Explanation:
The root of the tree already evaluates to false, so 0 nodes have to be flipped.
Constraints:
The number of nodes in the tree is in the range [1, 105].
0 <= Node.val <= 5
OR, AND, and XOR nodes have 2 children.
NOT nodes have 1 child.
Leaf nodes have a value of 0 or 1.
Non-leaf nodes have a value of 2, 3, 4, or 5.
Solutions
Solution 1
1 2 3 4 5 6 7 8 9101112131415161718192021222324
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defminimumFlips(self,root:Optional[TreeNode],result:bool)->int:defdfs(root:Optional[TreeNode])->(int,int):ifrootisNone:returninf,infx=root.valifxin(0,1):returnx,x^1l,r=dfs(root.left),dfs(root.right)ifx==2:returnl[0]+r[0],min(l[0]+r[1],l[1]+r[0],l[1]+r[1])ifx==3:returnmin(l[0]+r[0],l[0]+r[1],l[1]+r[0]),l[1]+r[1]ifx==4:returnmin(l[0]+r[0],l[1]+r[1]),min(l[0]+r[1],l[1]+r[0])returnmin(l[1],r[1]),min(l[0],r[0])returndfs(root)[int(result)]
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcminimumFlips(root*TreeNode,resultbool)int{vardfsfunc(*TreeNode)(int,int)dfs=func(root*TreeNode)(int,int){ifroot==nil{return1<<30,1<<30}x:=root.Valifx<2{returnx,x^1}l0,l1:=dfs(root.Left)r0,r1:=dfs(root.Right)vara,bintifx==2{a=l0+r0b=min(l0+r1,min(l1+r0,l1+r1))}elseifx==3{a=min(l0+r0,min(l0+r1,l1+r0))b=l1+r1}elseifx==4{a=min(l0+r0,l1+r1)b=min(l0+r1,l1+r0)}else{a=min(l1,r1)b=min(l0,r0)}returna,b}a,b:=dfs(root)ifresult{returnb}returna}