> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/my-algorithm-summary/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/my-algorithm-summary/data-structure/tree/285-inorder-successor-in-bst.md).

# 285 Inorder Successor in BST

## 285. Inorder Successor in BST

## 1. Question

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`.

## 2. Implementation

(1) Inorder traversal

```java
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode curNode = root, preNode = null;

        while (curNode != null || !stack.isEmpty()) {
            if (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            else {
                curNode = stack.pop();
                if (preNode != null && preNode == p) {
                    return curNode;
                }
                preNode = curNode;
                curNode = curNode.right;
            }
        }
        return null;
    }
}
```

(2) Binary Search

思路: 利用Binary Search Tree的二分特性

```java
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }

        TreeNode curNode = root;
        TreeNode successor = null;

        while (curNode != null) {
            if (curNode.val <= p.val) {
                curNode = curNode.right;
            }
            else {
                successor = curNode;
                curNode = curNode.left;
            }
        }
        return successor;
    }
}
```

## 3. Time & Space Complexity

Inorder Traversal: 时间复杂度: O(n), 空间复杂度: O(h)

Binary Search: 时间复杂度: O(logn), 空间复杂度: O(1)
