/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minimumOperations(root *TreeNode) (ans int) {
q := []*TreeNode{root}
for len(q) > 0 {
n := len(q)
a := make([]int, n)
tmp := q
q = nil
for i, node := range tmp {
a[i] = node.Val
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
id := make([]int, n) // 离散化后的数组
for i := range id {
id[i] = i
}
sort.Slice(id, func(i, j int) bool { return a[id[i]] < a[id[j]] })
ans += n
vis := make([]bool, n)
for _, v := range id {
if !vis[v] {
for ; !vis[v]; v = id[v] {
vis[v] = true
}
ans--
}
}
}
return
}
# 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 = right
# bfs + 置换环 + 离散化
class Solution:
def minimumOperations(self, root: Optional[TreeNode]) -> int:
ans, q = 0, [root]
while q:
a = []
tmp = q
q = []
for node in tmp:
a.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
n = len(a)
a = sorted(range(n), key=lambda i: a[i]) # 离散化
ans += n
vis = [False] * n
for v in a:
if vis[v]: continue
while not vis[v]:
vis[v] = True
v = a[v]
ans -= 1
return ans