As the note in the problem statement, this problem have a straight-forward O (n)-space solution, which is to genera Te the Inorder traversal results of the BST and then find the both nodes that violate the increasing trend and those is th E. requires to be swapped.
This link utilizes inorder traversal to find those, nodes without keeping all the results. However, inorder traversal implemented recursively would take at least O (LOGN) space and could even take O (n) space at the worst case. The code is rewritten as follows.
1 classSolution {2 Public:3 voidRecovertree (treenode*root) {4Pre = first = Second =NULL;5 inorder (root);6 if(first) {7 inttemp = FirstVal;8First--val = SecondVal;9Second, val =temp;Ten } One } A Private: -TreeNode *first, *second, *Pre; - voidInorder (treenode*root) { the if(!root)return; -Inorder (RootLeft ); - if(Pre && Pre, Val > rootval) { - if(!first) First =Pre; +Second =Root; - } +Pre =Root; AInorder (RootRight ); at } -};
So to come up with an O (1) -space Solution, we indeed has to turn to Morris traversal ...
[Leetcode] Recover Binary Search Tree