Skip to content

Commit 9ab9ab2

Browse files
authored
Create 2313-minimum-flips-in-binary-tree-to-get-result.js
1 parent 8574aee commit 9ab9ab2

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {boolean} result
12+
* @return {number}
13+
*/
14+
const minimumFlips = function (root, result) {
15+
const [FALSE, TRUE, OR, AND, XOR, NOT] = [0, 1, 2, 3, 4, 5]
16+
const costs = new Map()
17+
18+
const getMin = (node, target) => {
19+
if (node.val === FALSE || node.val === TRUE)
20+
return Math.abs(target - node.val)
21+
22+
const nodeCosts = costs.get(node) || [-1, -1]
23+
if (nodeCosts[target] >= 0) return nodeCosts[target]
24+
25+
if (node.val === NOT) {
26+
nodeCosts[target] = getMin(node.left || node.right, 1 - target)
27+
} else if (node.val === OR) {
28+
nodeCosts[target] =
29+
target === FALSE
30+
? getMin(node.left, 0) + getMin(node.right, 0)
31+
: Math.min(
32+
getMin(node.left, 0) + getMin(node.right, 1),
33+
getMin(node.left, 1) + getMin(node.right, 0),
34+
getMin(node.left, 1) + getMin(node.right, 1)
35+
)
36+
} else if (node.val === AND) {
37+
nodeCosts[target] =
38+
target === TRUE
39+
? getMin(node.left, 1) + getMin(node.right, 1)
40+
: Math.min(
41+
getMin(node.left, 0) + getMin(node.right, 1),
42+
getMin(node.left, 1) + getMin(node.right, 0),
43+
getMin(node.left, 0) + getMin(node.right, 0)
44+
)
45+
} else {
46+
nodeCosts[target] =
47+
target === FALSE
48+
? Math.min(
49+
getMin(node.left, 0) + getMin(node.right, 0),
50+
getMin(node.left, 1) + getMin(node.right, 1)
51+
)
52+
: Math.min(
53+
getMin(node.left, 0) + getMin(node.right, 1),
54+
getMin(node.left, 1) + getMin(node.right, 0)
55+
)
56+
}
57+
58+
costs.set(node, nodeCosts)
59+
return nodeCosts[target]
60+
}
61+
62+
return getMin(root, result ? 1 : 0)
63+
}

0 commit comments

Comments
 (0)