[LeetCode] Recover Binary Search Tree

99. Recover Binary Search Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<TreeNode*> WA;
TreeNode* prv = nullptr;
void helper(TreeNode* node) {
if(!node) return;
helper(node->left);
if(prv and prv->val > node->val) {
WA.push_back(prv);
while(WA.size() >= 2) WA.pop_back();
WA.push_back(node);
}
prv = node;
helper(node->right);

}
public:
void recoverTree(TreeNode* root) {
helper(root);
swap(WA[0]->val, WA[1]->val);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/19/PS/LeetCode/recover-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.