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?

C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10  void findSwap(TreeNode* root, TreeNode*& first, TreeNode*& second, TreeNode*& prv)
11  {
12      if(root==NULL)
13         return;
14      findSwap(root->left,first,second,prv);
15      if((prv!=NULL)&&(prv->val>root->val))
16      {
17          if(first==NULL)
18              first=prv;
19          second=root;
20      }
21      prv=root;
22      findSwap(root->right,first,second,prv);
23  }
24 
25 class Solution {
26 public:
27     void recoverTree(TreeNode *root) {
28         // Start typing your C/C++ solution below
29         // DO NOT write int main() function
30         TreeNode* first=NULL;
31         TreeNode* second=NULL;
32         TreeNode* prv=NULL;
33         findSwap(root,first,second,prv);
34         int t=first->val;
35         first->val=second->val;
36         second->val=t;
37     }
38 };
Advertisements
This entry was posted in Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s