[LeetCode] Minimum Flips in Binary Tree to Get Result

2313. Minimum Flips in Binary Tree to Get Result

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<TreeNode*, array<int, 2>> dp;
public:
int minimumFlips(TreeNode* t, bool r) {
int v = t->val;
if(dp.count(t) and dp[t][r] != -1) return dp[t][r];
if(!dp.count(t)) dp[t] = {-1, -1};
int& res = dp[t][r];
if(v <= 1) return res = r != v;

if(v == 2) return res = r ? min(minimumFlips(t->left, true), minimumFlips(t->right, true)) : minimumFlips(t->left, false) + minimumFlips(t->right, false);

if(v == 3) return res = r ? minimumFlips(t->left, true) + minimumFlips(t->right, true) : min(minimumFlips(t->left, false), minimumFlips(t->right, false));

if(v == 5) return res = t->left ? minimumFlips(t->left, !r) : minimumFlips(t->right, !r);

auto lt = minimumFlips(t->left, true), lf = minimumFlips(t->left, false);
auto rt = minimumFlips(t->right, true), rf = minimumFlips(t->right, false);

return res = r ? min(lt + rf, rt + lf) : min(lt + rt, lf + rf);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/26/PS/LeetCode/minimum-flips-in-binary-tree-to-get-result/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.