On the basis of the Middle-order traversal, find the non-standard (not incremental) Tree node pairs and then exchange
First, let's look at the two sequences:
1. 1 3 2 4 => Switch 3 and 2
2. 4 3 2 1 => exchange 4 and 1
These two sequences correspond to all possibilities of the intermediate traversal sequence of the BST that does not meet the condition.
If we use an array swap to save the result of non-incrementing traversal in the middle order, the array may only be 2 or 4 in size.
Instead, we only need to exchange the content of the first and last tree node pairs.
vector<TreeNode *> swap; TreeNode * pre; void recoverTree(TreeNode *root) { pre = new TreeNode(-999999); swap = vector<TreeNode *>(); inorder(root); if (swap.size() > 1) { int val = swap[0]->val; swap[0]->val = swap[swap.size() - 1]->val; swap[swap.size() - 1]->val = val; } } void inorder(TreeNode * root) { if (root == NULL) return; inorder(root->left); if (pre->val > root->val) { swap.push_back(pre); swap.push_back(root); } pre = root; inorder(root->right); }Since only the content of the first and last Tree nodes is exchanged, we can save only the first and last nodes
If (! First) First = pre;
Last = root;
Replace
Swap. push_back (pre); Swap. push_back (Root );
The Code is as follows:
TreeNode * first, * last; TreeNode * pre; void recoverTree(TreeNode *root) { pre = new TreeNode(-999999); first = last = NULL; inorder(root); if (first) { int val = first->val; first->val = last->val; last->val = val; } } void inorder(TreeNode * root) { if (root == NULL) return; inorder(root->left); if (pre->val > root->val) { if (!first) first = pre; last = root; } pre = root; inorder(root->right); }
Recover Binary Search Tree [leetcode]