[LeetCode] Inorder Successor in BST

285. Inorder Successor in BST

Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null.

The successor of a node p is the node with the smallest key greater than p.val.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(!root) return NULL;
if(root->val == p->val + 1) return root;
if(root->val < p->val + 1) return inorderSuccessor(root->right, p);
TreeNode* res = inorderSuccessor(root->left, p);
if(!res) res = root;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/19/PS/LeetCode/inorder-successor-in-bst-1/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.