码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Recover Binary Search Tree

时间:2015-01-15 23:35:43      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

中序遍历解法O(n)space
 
 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         vector<TreeNode *> nodes;
14         dfs(root,nodes);
15         int index1=-1;
16         int index2=-1;
17         for(int i=1;i<nodes.size();i++)
18         {
19             if(nodes[i]->val<nodes[i-1]->val)
20             {
21                 if(index1==-1) index1=i-1;
22                 index2=i;
23             }
24         }
25        
26         int tmp=nodes[index1]->val;
27         nodes[index1]->val=nodes[index2]->val;
28         nodes[index2]->val=tmp;
29         return;
30        
31     }     
32    
33     void dfs(TreeNode *root,vector<TreeNode *> &nodes)
34     {
35         if(root==NULL) return;
36         dfs(root->left,nodes);
37         nodes.push_back(root);
38         dfs(root->right,nodes);
39     }
40 };

 

 
 
直接在中序遍历中进行判断,需要记录遍历中的前一个元素
如果前一个元素比当前元素大,则说明存在错误
 
 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     
14         TreeNode *firstError=NULL;
15         TreeNode *secondError=NULL;
16         TreeNode *pre=NULL;
17 
18         
19         dfs(root,pre,firstError,secondError);
20         
21         int tmp=firstError->val;
22         firstError->val=secondError->val;
23         secondError->val=tmp;
24     }
25     
26     void dfs(TreeNode *root,TreeNode *&pre,TreeNode *&firstError,TreeNode *&secondError)
27     {
28         if(root==NULL) return;
29         
30         dfs(root->left,pre,firstError,secondError);
31         
32         if(pre!=NULL&&pre->val>root->val)
33         {
34             if(firstError==NULL) firstError=pre;
35             secondError=root;
36         }
37         pre=root;
38         
39         dfs(root->right,pre,firstError,secondError);
40     }
41 };

 

【leetcode】Recover Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4227478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!