# topic link

leetcode online oj question - the kth smallest element in a binary search tree

# topic description

Given a root node root of a binary search tree and an integer k, please design an algorithm to find the kth smallest element (counting from 1).

# Topic example

### Example 1

Input: root = [3,1,4,null,2], k = 1

Output: 1

### Example 2

Input: root = [5,3,6,2,4,null,null,1], k = 3

Output: 3

# Topic Tips

- The number of nodes in the tree is n.
- 1 <= k <= n <= 10^4
- 0 <= Node.val <= 10^4

# problem solving ideas

Since it is a binary search tree, we can traverse the tree directly in order, and then find the kth element from left to right to get the kth smallest element

Use non-recursive in-order traversal:

define a stack stack for storing traversed nodes, and define cur as the currently traversed node

First, cur traverses from the root node to the left subtree until null is traversed, and each time a node is traversed, it is pushed into the stack

At this time, cur is null, and the elements from the bottom of the stack to the top of the stack are arranged from large to small, and cur needs to return to the position of the previous traversal, cur = stack pops up an element, k–, (if k==0, return the current node directly value)

After cur traverses the left subtree, it starts to traverse the right subtree, cur = cur.right, if cur is null, let cur = stack pop up an element again

If cur is empty, you need to return to the last traversed position. If all positions have been traversed, there is no return position, that is, the stack is empty, and the loop ends. Therefore, the condition of the loop is: cur is not equal to empty or the

stack not null

# full code

```
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
do{
while(cur != null) {
stack.add(cur);
cur = cur.left;
}
if(!stack.isEmpty()) {
cur = stack.pop();
k--;
if(k == 0){
return cur.val;
}
}
cur = cur.right;
}while(cur != null || !stack.isEmpty());
return 0;
}
}
```