{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
\n", "\n", "
Example 1:
\n", "\n", "Input: root = [3,1,4,null,2], k = 1\n",
" 3\n",
" / \\\n",
" 1 4\n",
" \\\n",
" 2\n",
"Output: 1\n",
"\n",
"\n", "
Example 2:
\n", "\n", "Input: root = [5,3,6,2,4,null,null,1], k = 3\n",
" 5\n",
" / \\\n",
" 3 6\n",
" / \\\n",
" 2 4\n",
" /\n",
" 1\n",
"Output: 3\n",
"\n",
"\n",
"\n", "
Constraints:
\n", "\n", "1 to 10^4.k is always valid, 1 ≤ k ≤ BST's total elements.\n", "Source \n", "
Solve it both recursively and iteratively
\n", "What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
\n", "