[leetcode #230] Kth Smallest Element in a BST
1839 ワード
Problem
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?Idea
これは,与えられたBSTにおいてk番目に小数を求める問題である.
BSTをシーケンスとして探索し,ノード数を計算した.ノード数がkの場合、対応する値を返します.
Solution
/**
* 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);
}
}
Reference
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
Reference
この問題について([leetcode #230] Kth Smallest Element in a BST), 我々は、より多くの情報をここで見つけました https://velog.io/@timevoyage/leetcode-230-Kth-Smallest-Element-in-a-BSTテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol