# 230. Kth Smallest Element in a BST

![](/files/-MbjJv470xkZ3kD7wjcj)

![](/files/-MbjJy-xZIde3dLcoW0u)

## BST, and kth , order problem => think about inorder traversal

but be careful, the global variable count is necessary! (if use recursion)

or the result will change in the recursion process again

in this ex, k will pass into inorder(), twice, and all are  k = 1, so k-- , k == 0, there will be two times get the result, and the second will replace the first result!&#x20;

![](/files/-MlOUnp-IRdkqpgj1VZx)

even if you dont use global result, the behavior is the same, k = 1 pass to inorder twice

![](/files/-MlOVZmIaXcqb6Yl4TX0)

## traversal 都是遍例所有節點, 所以是 O(n), 因為 recursive 所以空間也需要 O(n)

**use count!**

time: O(n)

space: O(n)

```java
class Solution {
    
    int count = 0;
    int res = 0;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        helper(root, k);
        return res;
    }
    
    private void helper(TreeNode root, int k) {
        if (root == null) return;
        helper(root.left, k);
        count--;
        if (count == 0) {
            res = root.val;
        }
        helper(root.right, k);

    }
}
```

## stack - iteration

```java
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
        
        // k-1 times traversal
        for (int i = 0; i < k-1; i++) {
            TreeNode node = stack.pop();
            if (node.right != null) {
                node = node.right;
                
                while (node != null) {
                    stack.push(node);
                    node = node.left;
                }
            }
        }
        return stack.peek().val;
    }
}
```

## latest

early stop, if find k, we won't keep going, so&#x20;

T: O(k)

```java
/**
 * 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) {
        int[] curK = new int[1];
        curK[0] = k;
        int[] result = new int[1];
        dfs(root, curK, result);
        return result[0];
    }
    private void dfs(TreeNode node, int[] curK, int[] result) {
        if (node == null) {
            return;
        }
        if (curK[0] > 0) {
            dfs(node.left, curK, result);
        }

        curK[0]--;
        if (curK[0] == 0) {
            result[0] = node.val;
            return;
        }
        
        if (curK[0] > 0) {
            dfs(node.right, curK, result);
        }
    }
}
```


---

# 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://timmybeeflin.gitbook.io/cracking-leetcode/tree/230.-kth-smallest-element-in-a-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.
