diff --git a/cpp/2204/220419.cpp b/cpp/2204/220419.cpp new file mode 100644 index 0000000..8201582 --- /dev/null +++ b/cpp/2204/220419.cpp @@ -0,0 +1,50 @@ +#include +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x = 0, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(x), left(l), right(r) {} +}; + +/** + * 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. + */ + +class Solution { +public: + static void recoverTree(TreeNode* root) { + TreeNode* prev = nullptr, * x1 = nullptr, * x2 = nullptr; + std::function traverse = [&](TreeNode* r) { + if (!r) + return false; + if (r->left && traverse(r->left)) + return true; + + // Check if prevPrev < r + if (prev && prev->val >= r->val) { + x1 = r; + if (!x2) + x2 = prev; + else + return true; + } + prev = r; + + if (r->right) + return traverse(r->right); + return false; + }; + traverse(root); + std::swap(x1->val, x2->val); + } +}; + +int main() { + auto* root = new TreeNode(1, new TreeNode(3, nullptr, new TreeNode(2))); + Solution::recoverTree(root); + return 0; +} diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index df590e0..07a1feb 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220419-CN.cpp) +ADD_EXECUTABLE(2204 220419.cpp)