# 285. Inorder Successor in BST



T: O(n)

S: O(1)

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        
        TreeNode successor = null;
        while (root != null) {
            if (p.val >= root.val) {
                root = root.right;
            } else {
                successor = root;
                root = root.left;
            }
        }
        return successor;
    }
}

/*

   2
1     3

 
  因為是 inorder, 所以是  left root right
  所以往左走時, root 就是 potential  successor （因為 left root
  往右走則不是

*/
```
