You are given the root of a binary search tree (BST),
where the values of exactly two nodes of the tree were swapped by mistake.
Recover the tree without changing its structure.
EX. 1과 3이 바뀌었다, 둘을 바꿔준다.
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
self.temp = []
def dfs(node: TreeNode):
if not node: return
dfs(node.left)
self.temp.append(node)
dfs(node.right)
// inorder traversal으로 틀어진 부분을 찾는다.
dfs(root)
srt = sorted(n.val for n in self.temp)
tempdata = [n.val for n in self.temp]
a, b = 0, 0
for x, y in zip(srt, tempdata):
if x != y:
a, b = x, y
break
// 다른 부분을 찾아
// 다시 바꿔준다.
def revice(a: int, b: int, node: TreeNode):
if not node:
return
if node.val == a:
node.val = b
elif node.val == b:
node.val = a
revice(a, b, node.left)
revice(a, b, node.right)
revice(a, b, root)