Minimum Operations to Stabilize a Binary Tree Problem
Description
LeetCode Problem 4082.
You are given the root of a binary tree. Each node contains an integer value representing its current state.
A binary tree is considered stable if for every node u:
- If
u.leftexists, then|u.val - u.left.val| <= 1 - If
u.rightexists, then|u.val - u.right.val| <= 1
In one operation, you may choose any node and increase or decrease its value by 1.
Return the minimum number of operations required to make the entire binary tree stable.
Example 1:
Input: root = [5,8,3]
Output: 3
Explanation:

- Let u be the root node with value 5. Decrease the left child value from 8 to 6 using 2 operations. Then |u.val - u.left.val| = |5 - 6| = 1.
- Increase the right child value from 3 to 4 using 1 operation. Then |u.val - u.right.val| = |5 - 4| = 1.
- Thus, the answer is 2 + 1 = 3.
Example 2:
Input: root = [2,-1,-4]
Output: 5
Explanation:

- Let u be the root node with value 2. Decrease the value of u from 2 to −2 using 4 operations.
- Decrease the right child value from −4 to −3 using 1 operation. Then |u.val - u.right.val| = |-2 - (−3)| = 1.
- Thus, the answer is 4 + 1 = 5.
Example 3:
Input: root = [0,-2,2,-3,null,1]
Output: 3
Explanation:

- Let u be the root node with value 0. Increase the left child value from −2 to −1 using 1 operation, and decrease the right child value from 2 to 1 using 1 operation.
- Now |u.val - u.left.val| = |0 - (−1)| = 1 and |u.val - u.right.val| = |0 - 1| = 1.
- Let v be the left child of u, now having value −1. Increase its left child from −3 to −2 using 1 operation so that |v.val - v.left.val| = |−1 - (−2)| = 1.
- The right subtree already satisfies the condition since |1 - 1| = 0.
- Thus, the answer is 1 + 1 + 1 = 3.
Constraints:
- The number of nodes in the tree is in the range
[1, 5 * 10^4]. -10^5 <= Node.val <= 10^5
Solution
Approach: Tree DP with slope trick
Let f_v(x) be the least cost to fix the subtree of v when v ends up with the value x. Then
f_v(x) = |x - val(v)| + sum over children c of min(f_c(y) for |y - x| <= 1)
and every f_v is convex and piecewise linear. A convex function can be stored as its minimum minv plus two heaps of breakpoints: the left ones (a max-heap, each contributes (l - x)+) and the right ones (a min-heap, each contributes (x - r)+), with every left breakpoint at most every right one.
- Allowing a change of 1 (
minoverywithin 1 ofx) flattens the bottom of the function by one on each side: all left breakpoints move by-1and all right ones by+1. Keep two lazy offsets instead of touching the heaps. - Adding a function: merge the two heaps pairs, smaller into larger. Afterwards some left breakpoint
lcan exceed some right breakpointr; since(l - x)+ + (x - r)+ = (l - r) + (r - x)+ + (x - l)+, swap the two breakpoints between the heaps and addl - rtominv. Repeat while the largest left one is above the smallest right one. - Adding
|x - val|is one more left and one more right breakpoint atval.
Process the nodes from the last to the first in breadth-first order (so there is no deep recursion), merge each node's function into its parent, and the answer is minv of the root's function. Costs can reach about 10^10, so use 64-bit integers.
Complexity: O(n log^2 n) time with small-to-large merging, and O(n) space.
import heapq
class Solution:
def stabilizeBinaryTree(self, root: Optional[TreeNode]) -> int:
# The cost of a subtree as a function of its root's value x is convex. Keep it as
# minv + sum of (l - x)+ over the left breakpoints + sum of (x - r)+ over the right ones,
# with all left breakpoints <= all right ones (a "slope trick" function).
# state = [left max-heap (negated), right min-heap, left offset, right offset, minv]
def push_left(st, val):
heapq.heappush(st[0], -(val - st[2]))
def push_right(st, val):
heapq.heappush(st[1], val - st[3])
def fix(st):
# a pair l > r equals (l - r) + (r - x)+ + (x - l)+: swap them and pay l - r
while st[0] and st[1] and -st[0][0] + st[2] > st[1][0] + st[3]:
l = -heapq.heappop(st[0]) + st[2]
r = heapq.heappop(st[1]) + st[3]
st[4] += l - r
push_left(st, r)
push_right(st, l)
def merge(a, b):
if len(a[0]) + len(a[1]) < len(b[0]) + len(b[1]):
a, b = b, a
for v in b[0]:
push_left(a, -v + b[2])
for v in b[1]:
push_right(a, v + b[3])
a[4] += b[4]
fix(a)
return a
nodes = [root]
parent = [-1]
i = 0
while i < len(nodes):
for child in (nodes[i].left, nodes[i].right):
if child:
nodes.append(child)
parent.append(i)
i += 1
state = [None] * len(nodes)
for i in range(len(nodes) - 1, -1, -1):
st = state[i] or [[], [], 0, 0, 0] # the sum of the children's functions
push_left(st, nodes[i].val) # add |x - val|
push_right(st, nodes[i].val)
fix(st)
if parent[i] < 0:
return st[4]
# the parent may differ from this node by 1: the left part moves left, the right part moves right
st[2] -= 1
st[3] += 1
p = parent[i]
state[p] = st if state[p] is None else merge(state[p], st)
return 0