---
tags: leetcode
---
# [285. Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/)
---
# My Solution
## Solution 1: Use BST property
### The Key Idea for Solving This Coding Question
### C++ Code
```cpp=
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *inorderSuccessor(TreeNode *root, TreeNode *p) {
TreeNode *successor = nullptr;
while (root != nullptr) {
if (root->val <= p->val) {
root = root->right;
} else {
successor = root;
root = root->left;
}
}
return successor;
}
};
```
### Time Complexity
O(H), H is the height of BST.
### Space Complexity
O(1)
## Solution 2: DFS (iteration with stack, inorder traversal)
### The Key Idea for Solving This Coding Question
### C++ Code
```cpp=
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *inorderSuccessor(TreeNode *root, TreeNode *p) {
stack<TreeNode *> st;
bool isFound = false;
while (root != nullptr || !st.empty()) {
if (root != nullptr) {
st.push(root);
root = root->left;
} else {
root = st.top();
st.pop();
if (p == root) {
isFound = true;
} else if (isFound == true) {
return root;
}
root = root->right;
}
}
return nullptr;
}
};
```
### Time Complexity
O(n), n is the total number of nodes in BST.
### Space Complexity
O(H), H is the height of BST.
# Miscellaneous
<!--
# Test Cases
```
[2,1,3]
1
```
```
[5,3,6,2,4,null,null,1]
6
```
```
[2,null,3]
2
```
-->