https://leetcode.com/problems/recover-binary-search-tree/
空间解法!


个人解法

  1. class Solution:
  2. def recoverTree(self, root: Optional[TreeNode]) -> None:
  3. """
  4. Do not return anything, modify root in-place instead.
  5. """
  6. self.leftMax = -math.inf
  7. self.swapped = []
  8. def inorder(root):
  9. if not root:
  10. return
  11. inorder(root.left)
  12. if root.val < self.leftMax:
  13. if not self.swapped:
  14. self.swapped = [self.leftMax, root.val]
  15. else:
  16. self.swapped[1] = root.val
  17. self.leftMax = root.val
  18. inorder(root.right)
  19. inorder(root)
  20. def recover(root, swapped):
  21. if not root:
  22. return
  23. if root.val == swapped[0]:
  24. root.val = swapped[1]
  25. elif root.val == swapped[1]:
  26. root.val = swapped[0]
  27. recover(root.left, swapped)
  28. recover(root.right, swapped)
  29. recover(root, self.swapped)

题目分析

比较直观的方式是,根据BST的性质,中序遍历应该是有序的,只要中序遍历一遍,存下来,跟有序的对比一下就好。

  1. class Solution:
  2. def recoverTree(self, root: Optional[TreeNode]) -> None:
  3. """
  4. Do not return anything, modify root in-place instead.
  5. """
  6. def inorder(root):
  7. if not root:
  8. return []
  9. return inorder(root.left) + [root.val] + inorder(root.right)
  10. a = inorder(root)
  11. b = sorted(a)
  12. for i in range(len(a)):
  13. if a[i] != b[i]:
  14. swapped = [a[i], b[i]]
  15. break
  16. def recover(root, swapped):
  17. if not root:
  18. return
  19. if root.val == swapped[0]:
  20. root.val = swapped[1]
  21. elif root.val == swapped[1]:
  22. root.val = swapped[0]
  23. recover(root.left, swapped)
  24. recover(root.right, swapped)
  25. recover(root, swapped)

这样的空间复杂度是O(n),如果用固定空间,只能在中序遍历的过程中检测交换的节点了。
还是把握交换后的性质,中序遍历时不断更新遍历到的最大值,如果发现当前值比最大值小,那么必然存在问题,记录即可。