# Two elements of a binary search tree (BST) are swapped by mistake.# # Recover the tree without changing its structure.# # Note:# A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
AC
classTreeNode():def__init__(self, x):
self.val = x
self.left = None
self.right = NoneclassSolution():defrecoverTree(self, root):
self.lefty = None
self.righty = None
self._minnode = None
self._maxnode = None
self.preorder_visit(root)
self.postorder_visit(root)
# print self.lefty, self.righty
self.lefty.val, self.righty.val = self.righty.val, self.lefty.val
defpreorder_visit(self, node):# first check left and right treesif node.left:
self.preorder_visit(node.left)
if self.lefty:
returnif self._maxnode and node.val<self._maxnode.val:
self.lefty = self._maxnode
returnifnot self._maxnode or node.val > self._maxnode.val:
self._maxnode = node
if node.right:
self.preorder_visit(node.right)
defpostorder_visit(self, node):# first check left and right treesif node.right:
self.postorder_visit(node.right)
if self.righty:
returnif self._minnode and node.val > self._minnode.val:
self.righty = self._minnode
returnifnot self._minnode or node.val < self._minnode.val:
self._minnode = node
if node.left:
self.postorder_visit(node.left)
# Time: O(n)# Space: O(1)classTreeNode():def__init__(self, x):
self.val = x
self.left = None
self.right = NoneclassSolution2():defrecoverTree(self, root):return self.MorrisTraversal(root)
defMorrisTraversal(self, root):if root isNone:
return
broken = [None, None]
pre, cur = None, root
while cur:
if cur.left isNone:
self.detectBroken(broken, pre, cur)
pre = cur
cur = cur.right
else:
node = cur.left
while node.right and node.right != cur:
node = node.right
if node.right isNone:
node.right =cur
cur = cur.left
else:
self.detectBroken(broken, pre, cur)
node.right = None
pre = cur
cur = cur.right
broken[0].val, broken[1].val = broken[1].val, broken[0].val
return root
defdetectBroken(self, broken, pre, cur):if pre and pre.val > cur.val:
if broken[0] isNone:
broken[0] = pre
broken[1] = cur
if __name__ == "__main__":
root, root.left = TreeNode(0), TreeNode(1)
assert Solution().recoverTree(root) == None