Given the root of a binary search tree, and an integer k, return the kth smallest 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 <= 10⁴ · 0 <= Node.val <= 10⁴
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?
주어진 BST에서 k번째로 작은 수를 구하는 문제다.
BST를 inorder로 탐색하면서 노드 수를 센다. 노드 수가 k일 때 해당 값을 리턴하면 된다.
/**
* 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 {
int cnt = 0;
int ans = 0;
public int kthSmallest(TreeNode root, int k) {
inorder(root, k);
return ans;
}
private void inorder(TreeNode node, int k) {
if (node == null) {
return;
}
inorder(node.left, k);
cnt++;
if (cnt == k) {
ans = node.val;
}
inorder(node.right, k);
}
}
https://leetcode.com/problems/kth-smallest-element-in-a-bst/