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?

思路:

如果不限定空间的话,直接的办法是中序遍历的值放入一个数组,然后遍历这个数组,找到第一个前面大于后面的数的较大的数,再找最后一个前面大于后面的数的较小的数。因为要求是固定空间,所以用深搜实现,用pre和cur分别记录前一个和当前一个节点,如果pre>cur的话则记录错误节点,最后把错误节点的数值互换。

代码:

 1     TreeNode *pre, *cur, *n1, *n2;
 2     void search(TreeNode *root){
 3         if(!root)
 4             return;
 5         search(root->left);
 6         cur = root;
 7         if(pre && pre->val > cur->val){
 8             if(!n1){
 9                 n1 = pre;
10                 n2 = cur;
11             }
12             else{
13                 n2 = cur;
14             }
15         }
16         pre = root;
17         search(root->right);
18     }
19     void recoverTree(TreeNode *root) {
20         // IMPORTANT: Please reset any member data you declared, as
21         // the same Solution instance will be reused for each test case.
22         if(!root)
23             return;
24         pre = NULL;
25         cur = NULL;
26         n1 = NULL;
27         n2 = NULL;
28         search(root);
29         int tmp = n1->val;
30         n1->val = n2->val;
31         n2->val = tmp;
32     }

 第二遍传指针参数进去结果出了些问题,后来改成**好了。传参的概念有时候还是不太清晰。

 1     void search(TreeNode *root, TreeNode **pre, TreeNode **cur, TreeNode **n1, TreeNode **n2){
 2         if(root){
 3             search(root->left, pre, cur, n1, n2);
 4             *cur = root;
 5             if(*pre && (*pre)->val > (*cur)->val){
 6                 if(!*n1){
 7                     *n1 = *pre;
 8                 }
 9                 *n2 = *cur;
10             }
11             *pre = root;
12             search(root->right, pre, cur, n1, n2);
13         }
14     }
15     void recoverTree(TreeNode *root) {
16         // IMPORTANT: Please reset any member data you declared, as
17         // the same Solution instance will be reused for each test case.
18         TreeNode *pre = NULL, *cur = NULL, *n1 = NULL, *n2 = NULL;
19         search(root, &pre, &cur, &n1, &n2);
20         if(n1 && n2){
21             int tmp = n1->val;
22             n1->val = n2->val;
23             n2->val = tmp;
24         }
25     }

 

posted on 2013-11-13 15:46  waruzhi  阅读(181)  评论(0编辑  收藏  举报

导航