Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit09d8463

Browse files
authored
Updated recover.BST.md
1 parentc3583fc commit09d8463

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,78 @@
11
#Recover Binary Search Tree
22
###Problem link:[Click me](https://leetcode.com/problems/recover-binary-search-tree/)
33
---
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/)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp