CoderJesse  
wangjiexi@CS.PKU

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 class Solution {
 2 public:
 3     TreeNode *tmp;
 4     bool tag;
 5     bool key;
 6     TreeNode *tmp1;
 7     TreeNode *tmp2;
 8     void recoverTree(TreeNode *root) {
 9         // Start typing your C/C++ solution below
10         // DO NOT write int main() function
11         tmp1 = NULL;
12         tmp2 = NULL;
13         tag = false;
14         key = true;
15         check(root);
16         tag = false;
17         key = true;
18         check1(root);
19         if(tmp1 != NULL && tmp2 != NULL)
20         {
21             int m = tmp1->val;
22             tmp1->val = tmp2->val;
23             tmp2->val = m;
24         }
25     }
26     void check(TreeNode *root)
27     {
28         if(key == false)
29             return;
30         if(root == NULL)
31             return;
32         check(root->left);
33         if(tag == false)
34         {
35             tmp = root;
36             tag = true;
37         }
38         else
39         {
40             if(root->val <= tmp->val)
41             {
42                 tmp1 = tmp;
43                 key = false;
44             }
45             else
46                 tmp = root;
47         }
48         check(root->right);
49     }
50     void check1(TreeNode *root)
51     {
52         if(key == false)
53             return;
54         if(root == NULL)
55             return;
56         check1(root->right);
57         if(tag == false)
58         {
59             tmp = root;
60             tag = true;
61         }
62         else
63         {
64             if(root->val >= tmp->val)
65             {
66                 tmp2 = tmp;
67                 key = false;
68             }
69             else
70                 tmp = root;
71         }
72         check1(root->left);
73     }
74 };

 

posted on 2013-03-01 13:37  CoderJesse  阅读(121)  评论(0)    收藏  举报