[LeetCode] Inorder Successor in BST II

510. Inorder Successor in BST II

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

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

You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for Node:

1
2
3
4
5
6
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* parent;
};
*/

class Solution {
Node* findRightChild(Node* node, int val) {
while(node->left and node->left->val > val)
node = node->left;
return node;
}
Node* findParentRightChild(Node* node, int val) {
while(node) {
if(node->val > val) return node;
if(node->right and node->right->val > val)
return findRightChild(node->right, val);
node = node->parent;
}
return node;
}
public:
Node* inorderSuccessor(Node* node) {
if(node->right != NULL) return findRightChild(node->right, node->val);
if(node->parent != NULL) return findParentRightChild(node->parent, node->val);

return NULL;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/inorder-successor-in-bst-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.