LeetCode Recover Binary Search Tree——二查搜索树中两个节点错误

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. Could you devise a constant space solution?二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。
最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。
但这种方法要求n的空间复杂度,题目中要求空间复杂度为常数,所以需要换一种方法。
递归中序遍历二叉树,设置一个pre指针,记录当前节点中序遍历时的前节点,如果当前节点大于pre节点的值,说明需要调整次序。
有一个技巧是如果遍历整个序列过程中只出现了一次次序错误,说明就是这两个相邻节点需要被交换。如果出现了两次次序错误,那就需要交换这两个节点,这两个节点一个是前次错误的pre,一个的后次错误的root。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void recoverTree(TreeNode *root) {
13         if(root==NULL) return;
14         pre=NULL;
15         mistake1=NULL;
16         mistake2=NULL;
17         recover(root);
18         if(mistake1!=NULL&&mistake2!=NULL){
19             swap(mistake1->val,mistake2->val);
20         }
21     }
22     void recover(TreeNode *root){
23         if(root==NULL) return;
24         if(root->left!=NULL) recover(root->left);
25         if(pre!=NULL&&pre->val>root->val){
26             if(mistake1==NULL){
27                 mistake1=pre;
28                 mistake2=root;
29             }else{
30                 mistake2=root;
31             }
32         }
33         pre=root;
34         if(root->right!=NULL) recover(root->right);
35     }
36     TreeNode *pre;
37     TreeNode *mistake1,*mistake2;
38 };
原文地址:https://www.cnblogs.com/zl1991/p/7045871.html