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?
Analysis: Two cross-tree traversal algorithms are available in a number of scenarios, and this is a good example. One of the features of BST is that its middle sequence traversal is ascending, so we can determine which of the two elements of the value interchange by the BST's middle order ratio traversal, where the requirement is constant space, so it is natural to think of the O (1) space complexity of the Morris sequence traversal. We swapped two elements with a pair record value, and finally exchanged their values. The code is as follows:
classSolution { Public: voidRecovertree (TreeNode *root) {TreeNode*cur =Root; TreeNode*prev =NULL; Pair<treenode *, TreeNode *>broken; while(cur) {if(Cur->left = =NULL) {Detect (broken, prev, cur); Prev=cur; Cur= cur->Right ; }Else{TreeNode*node = cur->Left ; for(; Node->right && node->right! = cur; node = node->Right ); if(Node->right = =NULL) {Node->right =cur; Cur= cur->Left ; }Else{node->right =NULL; Detect (broken, prev, cur); Prev=cur; Cur= cur->Right ; }}} swap (Broken.first->val, broken.second->val); } voidDetect (Pair<treenode *, TreeNode *> &broken, TreeNode *prev, TreeNode *cur) { if(prev! = NULL && prev->val > cur->val) { if(Broken.first = =NULL) {Broken.first=prev; } Broken.second=cur; } }};
Leetcode:recover Binary Search Tree