diff --git a/cpp/2205/220516-CN.cpp b/cpp/2205/220516-CN.cpp new file mode 100644 index 0000000..4591e9b --- /dev/null +++ b/cpp/2205/220516-CN.cpp @@ -0,0 +1,36 @@ +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {} +}; + +/** + * 面试题 04.06. Successor LCCI + * Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. + * Return null if there's no "next" node for the given node. + */ + +class Solution { +public: + static TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { + if (!root || !p) + return nullptr; + // Target value: p->val; + TreeNode* ret = nullptr; + for (auto* ptr = root; ptr; ) { + if (ptr->val == p->val) { + for (ptr = ptr->right; ptr && ptr->left; ptr = ptr->left); + return ptr ? ptr : ret; + } else if (ptr->val < p->val) { + ptr = ptr->right; + } else { + ret = ptr; + ptr = ptr->left; + } + } + return ret; + } +}; diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index af82855..f611761 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220516.cpp) +ADD_EXECUTABLE(2205 220516-CN.cpp)