https://leetcode.com/problems/recover-binary-search-tree/
空间解法!
个人解法
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.leftMax = -math.inf
self.swapped = []
def inorder(root):
if not root:
return
inorder(root.left)
if root.val < self.leftMax:
if not self.swapped:
self.swapped = [self.leftMax, root.val]
else:
self.swapped[1] = root.val
self.leftMax = root.val
inorder(root.right)
inorder(root)
def recover(root, swapped):
if not root:
return
if root.val == swapped[0]:
root.val = swapped[1]
elif root.val == swapped[1]:
root.val = swapped[0]
recover(root.left, swapped)
recover(root.right, swapped)
recover(root, self.swapped)
题目分析
比较直观的方式是,根据BST的性质,中序遍历应该是有序的,只要中序遍历一遍,存下来,跟有序的对比一下就好。
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def inorder(root):
if not root:
return []
return inorder(root.left) + [root.val] + inorder(root.right)
a = inorder(root)
b = sorted(a)
for i in range(len(a)):
if a[i] != b[i]:
swapped = [a[i], b[i]]
break
def recover(root, swapped):
if not root:
return
if root.val == swapped[0]:
root.val = swapped[1]
elif root.val == swapped[1]:
root.val = swapped[0]
recover(root.left, swapped)
recover(root.right, swapped)
recover(root, swapped)
这样的空间复杂度是O(n),如果用固定空间,只能在中序遍历的过程中检测交换的节点了。
还是把握交换后的性质,中序遍历时不断更新遍历到的最大值,如果发现当前值比最大值小,那么必然存在问题,记录即可。