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?
Algorithm one, middle sequence traversal
Recursion in the sequence of the duration. While traversing, a prev pointer is maintained, pointing to the previous element of the current element.
Identify the two nodes in the order of violation. and stored down.
Violations are divided into two types:
1. The two nodes of the adjacent element are exchanged. In this case, in the middle sequence traversal, only one violation is detected (violation: The value of the preceding node is greater than the value of the current node).
2. Two nodes of nonadjacent elements are exchanged. In this case, there will be two violations in the middle sequence traversal.
The actual execution time on the Leetcode is 101ms.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: void Recovertree (treenode* root) { TreeNode *prev = 0, *first = 0, *second = 0; Helper (Root, prev, first, second); Swap (First->val, second->val); } void Helper (TreeNode *root, TreeNode *&prev, TreeNode *&first, TreeNode *&second) { if (!root) return;
helper (Root->left, Prev, first, second); if (prev && prev->val > Root->val) { if (!first) {First = prev; second = root; } else { second = root; return; } } prev = root; Helper (Root->right, Prev, first, second); };
Algorithm two: Morris traversal
Use Morris traversal instead of recursive invocation.
Other ibid.
The actual execution time on the Leetcode is 131ms.
Time is longer than algorithm. The reason is that in algorithm one, when a second violation is found. The stack is rolled back directly. May save a fraction of the time.
Morris, however, needs to restore the right pointer to be reused. So you need to traverse to the end.
Class Solution {Public:void recovertree (treenode* root) {TreeNode *first = 0, *second = 0, *prev = 0; while (root) {if (!root->left) {if (prev && prev->val > Root->val) { second = root; if (!first) first = prev; } prev = root; root = root->right; } else {TreeNode *p = root->left; while (p->right && p->right! = root) p = p->right; if (!p->right) {p->right = root; root = root->left; } else {p->right = 0; if (prev && prev->val > Root->val) {second = root; if (!first) first = prev; } prev = root; root = root->right; }}} if (first && second) swap (first->val, second->val); }};
Recover Binary Search Tree--Leetcode