# 285 inorder successor in BST

感觉这种办法最直观，做inorder traverse并keep track of current index，如果找到了就看下一个index的node是哪个，要注意idx应该是全局变量，同时find不能有返回值，因为是不能立刻返回的

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int idx = -1;
    private int cnt = 0;
    private TreeNode ans = null;
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        find(root, p);
        return ans;
    }
    private void find(TreeNode root, TreeNode p) {
        if (root == null) return;
        find(root.left, p);
        cnt++;
        if (root.val == p.val) idx = cnt;
        if (idx > 0 && idx + 1 == cnt) ans = root;
        find(root.right, p);
    }
}
```

或者可以利用BST特性剪枝

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int idx = -1;
    private int cnt = 0;
    private TreeNode ans = null;
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        find(root, p);
        return ans;
    }
    private void find(TreeNode root, TreeNode p) {
        if (root == null) return;
        if (root.val > p.val) find(root.left, p);
        cnt++;
        if (root.val == p.val) idx = cnt;
        if (idx > 0 && idx + 1 == cnt) ans = root;
        find(root.right, p);
    }
}
```


---

# 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://hzhang.gitbook.io/leetcode-record/bst-binary-search-tree/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.
