From d5ea71dbc18b2f25ad1c3123b15206e810418dbf Mon Sep 17 00:00:00 2001 From: Prad Nukala Date: Sat, 5 Sep 2026 16:28:18 -0400 Subject: [PATCH] =?UTF-8?q?docs(docs):=20add=20MDX=20page=20for=20?= =?UTF-8?q?=E2=80=9C230.=20Kth=20Smallest=20Element=20in=20a=20BST?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../230-kth-smallest-element-in-a-bst.mdx | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 apps/docs/content/(tree)/230-kth-smallest-element-in-a-bst.mdx diff --git a/apps/docs/content/(tree)/230-kth-smallest-element-in-a-bst.mdx b/apps/docs/content/(tree)/230-kth-smallest-element-in-a-bst.mdx new file mode 100644 index 0000000..5af1d7a --- /dev/null +++ b/apps/docs/content/(tree)/230-kth-smallest-element-in-a-bst.mdx @@ -0,0 +1,54 @@ +--- +title: '230. Kth Smallest Element in a BST' +description: Given the root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree +sidebar: + label: 'Kth Smallest Element in a BST' + badge: 'Medium' +--- + +Binary Search Tree + +::::warning +If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? +:::: + +### 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` + +### Constraints: + +- The number of nodes in the tree is n. +- `1 <= k <= n <= 10^4` +- `0 <= Node.val <= 10^4` + +## Solution + +```py +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + n = 0 + stack = [] + cur = root + + while cur or stack: + while cur: + stack.append(cur) + cur = cur.left + + cur = stack.pop() + n += 1 + if n == k: + return cur.val + cur = cur.right +```