|
1 | 1 | #Recover Binary Search Tree |
2 | 2 | ###Problem link:[Click me](https://leetcode.com/problems/recover-binary-search-tree/) |
3 | 3 | --- |
| 4 | +-##Question: |
| 5 | +>You are given the`root` of a binary search tree (BST), where the values of**exactly** two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. |
| 6 | +>>Example : |
| 7 | +
|
| 8 | + 1 3 |
| 9 | + / / |
| 10 | + 3 ➡️ 1 |
| 11 | + \ \ |
| 12 | + 2 2 |
| 13 | +
|
| 14 | +
|
| 15 | +Input: root = [1,3,null,null,2] |
| 16 | +Output: [3,1,null,null,2] |
| 17 | +Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. |
| 18 | + |
| 19 | +--- |
| 20 | + |
| 21 | +-##Solution: |
| 22 | +**Code :(Approach: Recursive)** |
| 23 | + |
| 24 | +```cpp |
| 25 | +/** |
| 26 | + * Definition for a binary tree node. |
| 27 | + * struct TreeNode { |
| 28 | + * int val; |
| 29 | + * TreeNode *left; |
| 30 | + * TreeNode *right; |
| 31 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 32 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 33 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 34 | + * }; |
| 35 | +*/ |
| 36 | +classSolution { |
| 37 | +public: |
| 38 | + void recoverTree(TreeNode* root) { |
| 39 | + inorder(root); |
| 40 | + swap(x, y); |
| 41 | + } |
| 42 | + |
| 43 | + private: |
| 44 | + TreeNode* pred = nullptr; |
| 45 | + TreeNode* x = nullptr; // 1st wrong node |
| 46 | + TreeNode* y = nullptr; // 2nd wrond node |
| 47 | + |
| 48 | + void inorder(TreeNode* root) { |
| 49 | + if (!root) |
| 50 | + return; |
| 51 | + |
| 52 | +inorder(root->left); |
| 53 | + |
| 54 | +if (pred && root->val < pred->val) { |
| 55 | + y = root; |
| 56 | + if (!x) |
| 57 | + x = pred; |
| 58 | + else |
| 59 | + return; |
| 60 | +} |
| 61 | + pred = root; |
| 62 | + |
| 63 | +inorder(root->right); |
| 64 | + } |
| 65 | + |
| 66 | + void swap(TreeNode* x, TreeNode* y) { |
| 67 | + const int temp = x->val; |
| 68 | + x->val = y->val; |
| 69 | + y->val = temp; |
| 70 | + |
| 71 | + } |
| 72 | +}; |
| 73 | +``` |
| 74 | +**Time Complexity : O(n)** |
| 75 | +
|
| 76 | +--- |
| 77 | +
|
| 78 | +Reference : [Dev to](https://dev.to/) |