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. cocould you devise a constant space solution?
Idea: recursively traverse the input binary tree in the middle order. For a binary search tree, the sequential traversal results in an incremental sequence. Because two elements in the input binary search tree are exchanged, what we get is not an incremental sequence.
Suppose the incremental sequence: {1, 2, 3, 4, 5}. Obviously, there are two conditions for exchanging two elements: one is that the two elements to be exchanged are adjacent, such as switching 1 and 2, {, 5} is obtained. The other is that the two elements to be exchanged are not adjacent. For example, if one or three elements are exchanged, {, 5} is obtained }. In the first case, a reverse order pair ({}) appears in the order traversal sequence, and in the second case, two reverse order pairs ({} and {}) appear in the order traversal sequence }. Therefore, we only need to find the reverse order pairs in the middle order traversal sequence to complete the correction of the Binary Search Tree.
To compare Adjacent Elements in a recursive call, use the global pointer pre to indicate the elements output one time before. The size of the current output element and the previous output element is compared each time. If it is a backward direction, the global pointer first and second are used to point to them respectively. If the current backward direction is the second backward direction, we only need to modify the second pointer to point it to the current element.
1 class Solution { 2 public: 3 void recoverTree( TreeNode *root ) { 4 prev = first = second = 0; 5 InOrder( root ); 6 if( first ) { swap( first->val, second->val ); } 7 return; 8 } 9 private:10 void InOrder( TreeNode*& node ) {11 if( !node ) { return; }12 InOrder( node->left );13 if( prev && prev->val > node->val ) {14 second = node;15 if( !first ) { first = prev; }16 }17 prev = node;18 InOrder( node->right );19 }20 TreeNode *prev, *first, *second;21 };