class Solution {
public:
bool isTarget = false;
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(root == nullptr) return nullptr;
TreeNode* left = inorderSuccessor(root->left, p);
if(left != nullptr) return left;
if(isTarget){
return root;
}
if(p->val == root->val){
isTarget = true;
}
TreeNode* right = inorderSuccessor(root->right, p);
if(right != nullptr) return right;
return nullptr;
}
};
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* sucessor = nullptr;
while(root != nullptr){
if(root->val <= p->val){
root = root->right;
} else {
sucessor = root;
root = root->left;
}
}
return sucessor;
}
};