classSolution(object): defrecoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ # inorder traversal cur = root ss = [] prev = TreeNode(float('-inf')) first = second = None while ss or cur: if cur: ss.append(cur) cur = cur.left else: cur = ss.pop() # visit cur if cur.val < prev.val: ifnot first: first = prev second = cur prev = cur cur = cur.right first.val, second.val = second.val, first.val
classSolution(object): defrecoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ # inorder traversal cur = root prev = None first = second = None while cur: ifnot cur.left: # visit cur if prev and cur.val < prev.val: ifnot first: first = prev second = cur prev = cur cur = cur.right else: node = cur.left while node.right and node.right != cur: node = node.right ifnot node.right: # not threaded yet node.right = cur cur = cur.left else: # already threaded node.right = None # visit cur if prev and cur.val < prev.val: ifnot first: first = prev second = cur prev = cur cur = cur.right