Given the root of a binary search tree and the value p of a node in it, return the in-order successor of that node. If the node has no in-order successor in the tree, return None.
The successor of p is the node with the smallest value greater than p.
Function Signature
def inorder_successor(root: TreeNode, p: int) -> int | None:
Rules
-
The tree is passed as its root
TreeNode
, with fields
val
,
left
and
right
. The examples write the tree as a level-order list where
None
marks a missing child.
-
p
is the value of a node in the tree. Return the value of the successor node, or
None
when
p
is the largest value in the tree.
Constraints
-
The number of nodes in the tree is in the range 1 to
10^4
.
-
-10^5 <= Node.val <= 10^5
-
All node values are unique.
-
p
exists in the tree.
Examples
Input: root = [2,1,3], p = 1
Output: 2
The in-order traversal is [1, 2, 3], so the value after 1 is 2.
Input: root = [5,3,6,2,4,None,None,1], p = 6
Output: None
The in-order traversal is [1, 2, 3, 4, 5, 6]. Node 6 holds the largest value, so it has no successor.
Input: root = [2,1,5,None,None,3,6], p = 2
Output: 3
The in-order traversal is [1, 2, 3, 5, 6], so the value after 2 is 3.