Elements of a binary search tree (BST) is 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?
Requires locating two nodes in the wrong location in BST.
The intuitive idea is to use the middle sequence traversal to solve. A normal BST, its normal sequence of sequential traversal is an ascending sequence (non-descending, if there is a repeating element). So if there are elements being exchanged, there will be a decrease. If it is not a previous successor of two nodes, then only one reversal will occur, and if not, It will appear two times, for example, as follows:
1 2 3 4 5 6 7 This is a normal BST sequential traversal sequence. If the previous two nodes, such as the 3,4 interchange, the sequence traversal sequences are: 1 2 4 3 5 6 7. 4 3 A reverse order occurs. If it is not the back-and-forth, such as 3,5 exchange, then the middle order traversal is 1 2 5 4 3 6 7. Then 5 4, 4 3 is in reverse order. You can see that in the first reversed pair, the previous value is the first reverse-order node. In the latter case, a value is the inverse of the reverse. In the case where there is only one reverse pair, the previous value is the first reverse-order node, and the latter value is the second reverse-order node. The time complexity is O (n). The spatial complexity is O (NLOGN). The code is as follows:
#Definition for a binary tree node.#class TreeNode (object):#def __init__ (self, x):#self.val = x#self.left = None#self.right = Noneclasssolution (object):defRecovertree (self, root):""": Type root:TreeNode:rtype:void do not return anything, modify root in-place instead. """ if notRoot:returnStack=[] Prev= TreeNode (-sys.maxint-1) cur=Root former=None Latter=None whileStackorcur:ifcur:stack.append (cur) cur=Cur.leftElse: Cur=Stack.pop ()ifCur.val <Prev.val:if notFormer:former=Prev Latter=cur prev=curElse: Latter=cur Break Else: Prev=cur cur=cur.right Former.val, Latter.val= Latter.val, Former.val
The O (1) space complexity required for the topic needs to be done in conjunction with the Morris Traversal, see http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html
Recover Binary Search Tree