Given the root of a binary search tree, and an integer k, return thekthsmallest value (1-indexed) of all the values of the nodes in the tree.
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 <= 104
0 <= Node.val <= 104
Follow up: 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?
ac1: Recusive
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */// BST-> in-order traversalclassSolution {publicintkthSmallest(TreeNode root,int k) {// edge casesif (root ==null|| k <1) return-1;List<Integer> res =newArrayList<Integer>();helper(root, k, res);returnres.get(0); }privateinthelper(TreeNode root,int k,List<Integer> res) {// exitif (root ==null|| k <0) return k;// handle k =helper(root.left, k, res);if (k ==-1) {return-1; } elseif (k ==1) {res.add(root.val);return-1; } else {returnhelper(root.right, k-1, res); } }}// in-order traversal
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicintkthSmallest(TreeNode root,int k) {TreeNode r = root;Stack<TreeNode> stack =newStack<>();int res =0;while (!stack.isEmpty() || r !=null) {while (r !=null) {stack.push(r); r =r.left; } r =stack.pop(); k--;if (k ==0) res =r.val; r =r.right; }return res; }}