面试题20:搜索二叉树可能有两个元素发生了交换,如何恢复BST?

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

 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     TreeNode* pre = nullptr;
13     TreeNode* mistake1 = nullptr;
14     TreeNode* mistake2 = nullptr;
15     void recoverTree(TreeNode *root) {
16         inorder(root);
17         if(mistake1 && mistake2) swap(mistake1->val,mistake2->val);
18     }
19     void inorder(TreeNode* root){
20         if(root == nullptr) return ;
21         inorder(root->left);
22         if(pre == nullptr) pre = root;
23         else{
24             if(pre->val > root->val){
25                 if(mistake1 == nullptr) mistake1=pre;
26                 mistake2 = root;
27             }
28             pre = root;
29         }
30         inorder(root->right);
31     }
32 };

 

posted @ 2017-05-16 22:44  wxquare  阅读(482)  评论(0编辑  收藏  举报