LeetCode Solutions
285. Inorder Successor in BST
Time: $O(n)$ Space: $O(h)$
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if (root == nullptr)
return nullptr;
if (root->val <= p->val)
return inorderSuccessor(root->right, p);
TreeNode* left = inorderSuccessor(root->left, p);
return left ? left : root;
}
};
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null)
return null;
if (root.val <= p.val)
return inorderSuccessor(root.right, p);
TreeNode left = inorderSuccessor(root.left, p);
return left == null ? root : left;
}
}
class Solution:
def inorderSuccessor(self, root: Optional[TreeNode], p: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
if root.val <= p.val:
return self.inorderSuccessor(root.right, p)
return self.inorderSuccessor(root.left, p) or root