# 285 Inorder Successor in BST

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

**Note**: If the given node has no in-order successor in the tree, return`null`.

**The Idea:** The problem can be summed up into two cases. In the first case when `p` has a right child, then the next in order successor is the smallest value of that right subtree. Otherwise, we have to ascend down from the root of the tree and find `p` using plain old binary search. In this case, maintain a previous node that follows `root.left`, since this will be the the first largest node that is larger than root once `p` is found.

**Complexity:** O(logn) time and O(1) space

```python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode - the actual root of the tree
        :type p: TreeNode - find the next in order successor of this node
        :rtype: TreeNode
        """
        if not root or not p:
            return None

        # case 1
        if p.right:
            p = p.right
            while p.left:
                p = p.left
            return p

        # case 2
        prev = None
        while root != p:
            if p.val > root.val:
                root = root.right
            else:
                prev = root
                root = root.left
        return prev
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/285-inorder-successor-in-bst.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
