99. Recover Binary Search Tree 恢复二叉搜索树

二叉搜索树中的两个节点被错误地交换。

请在不改变其结构的情况下,恢复这棵树。

示例 1:

输入: [1,3,null,null,2]

   1
  /
 3
  \
   2

输出: [3,1,null,null,2]

   3
  /
 1
  \
   2

示例 2:

输入: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

输出: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

进阶:

  1. 使用 O(n) 空间复杂度的解法很容易实现。
  2. 你能想出一个只使用常数空间的解决方案吗?

中序遍历

提到二叉搜索树,首先想到中序遍历,因为BST的中序遍历结果是排好序的,所以将排序的中序遍历结果和未排序的中序遍历结果中不同的节点交换即可。

Code

	def recoverTree(self, root: TreeNode) -> None:
		"""
        Do not return anything, modify root in-place instead.
        """
		Trees = lambda x: [] if not x else Trees(x.left) + [x] + Trees(x.right)
		a = Trees(root)
		sa = sorted(a, key=lambda x: x.val)
		temp = [a[i] for i in range(len(a)) if a[i] != sa[i]]
		temp[0].val, temp[1].val = temp[1].val, temp[0].val

猜你喜欢

转载自blog.csdn.net/weixin_43336281/article/details/107874572