class Solution:
def minimumOperations(self, root: Optional[TreeNode]) -> int:
visit = [0 for _ in range(100001)]
ans = 0
def cycle_shape(h, v):
identity = sorted(h)
permutation = {}
ret = 0
for x, fx in zip(identity, h):
permutation[x] = fx
for node in h:
if v[node] == 1:
continue
count = 0
while v[node] == 0:
v[node] = 1
node = permutation[node]
count += 1
ret += count - 1
return ret
ch, height = 0, []
queue = deque([(root, 0)])
while queue:
cur, depth = queue.popleft()
if depth > ch:
ans += cycle_shape(height, visit)
ch += 1
height = []
if cur.left:
height.append(cur.left.val)
queue.append((cur.left, depth + 1))
if cur.right:
height.append(cur.right.val)
queue.append((cur.right, depth + 1))
return ans + cycle_shape(height, visit)
하필 이브에 나온 문제는 구현이 귀찮아서 버려둠.. 답은 알겠다만..
n-cycle은 n-1번 swap하면 identity map이 되고 이게 최소 횟수입니다
댓글 영역
획득법
① NFT 발행
작성한 게시물을 NFT로 발행하면 일주일 동안 사용할 수 있습니다. (최초 1회)
② NFT 구매
다른 이용자의 NFT를 구매하면 한 달 동안 사용할 수 있습니다. (구매 시마다 갱신)
사용법
디시콘에서지갑연결시 바로 사용 가능합니다.