The in-order traversal of a binary search tree is an ascending sequence, so we can use the binary search method.
The in-order successor node of a binary search tree node $p$ satisfies:
The value of the in-order successor node is greater than the value of node $p$.
The in-order successor is the node with the smallest value among all nodes greater than $p$.
Therefore, for the current node $root$, if $root.val > p.val$, then $root$ could be the in-order successor of $p$. We record $root$ as $ans$ and then search the left subtree, i.e., $root = root.left$. If $root.val \leq p.val$, then $root$ cannot be the in-order successor of $p$, and we search the right subtree, i.e., $root = root.right$.
The time complexity is $O(h)$, where $h$ is the height of the binary search tree. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 9101112131415161718
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:definorderSuccessor(self,root:TreeNode,p:TreeNode)->Optional[TreeNode]:ans=Nonewhileroot:ifroot.val>p.val:ans=rootroot=root.leftelse:root=root.rightreturnans
1 2 3 4 5 6 7 8 91011121314151617181920212223
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{publicTreeNodeinorderSuccessor(TreeNoderoot,TreeNodep){TreeNodeans=null;while(root!=null){if(root.val>p.val){ans=root;root=root.left;}else{root=root.right;}}returnans;}}
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSolution{public:TreeNode*inorderSuccessor(TreeNode*root,TreeNode*p){TreeNode*ans=nullptr;while(root){if(root->val>p->val){ans=root;root=root->left;}else{root=root->right;}}returnans;}};
1 2 3 4 5 6 7 8 910111213141516171819
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcinorderSuccessor(root*TreeNode,p*TreeNode)(ans*TreeNode){forroot!=nil{ifroot.Val>p.Val{ans=rootroot=root.Left}else{root=root.Right}}return}