99. 恢复二叉搜索树
问题描述
https://leetcode.cn/problems/recover-binary-search-tree/description/
解题思路
二叉搜索树的中序遍历一定是一个有序的序列。
题目中说两个节点的值被交换了,即我们中序遍历得到的二叉搜索树是无序的,但交换两个节点即为有序。
所以,我们可以:
- 深度优先搜索,搞到二叉搜索树的序列。
- 将这个序列排序,再次遍历,找到需要交换值的节点。
- 将值进行交换。
代码
# 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 class Solution: def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ li = [] def dfs(root): if not root: return dfs(root.left) li.append((root.val, root)) dfs(root.right) dfs(root) li_sort = sorted(li, key=lambda x: x[0]) swaped = [] for i in range(len(li)): if li[i][0] != li_sort[i][0]: swaped.append(li[i][1]) x, y = swaped x.val, y.val = y.val, x.val
2024二刷:
# 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 class Solution: def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ mem = [] vals = [] def dfs(root): if root: dfs(root.left) mem.append(root) vals.append(root.val) dfs(root.right) dfs(root) vals.sort() for i in range(len(mem)): mem[i].val = vals[i]