add: 220516-CN [cpp]

This commit is contained in:
eat-swap 2022-05-16 16:01:04 +08:00
parent b3fde21416
commit 6f93cb693e
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 37 additions and 1 deletions

36
cpp/2205/220516-CN.cpp Normal file
View File

@ -0,0 +1,36 @@
#include <iostream>
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;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2205 220516.cpp)
ADD_EXECUTABLE(2205 220516-CN.cpp)