[英]Finding kth smallest element in an array using Binary Search Tree
問題是找到數組中的“第 K 個”最小元素。 https://practice.geeksforgeeks.org/problems/kth-smallest-element/0
現在我確實看到了給定的技術,但無法正確理解它們。 看到這個問題后,我的第一個直覺是從給定的數組創建一個 BST,並使用 BST 的 InOrder Traversal 找到數組的“第 K 個”最小元素。 這是我的方法的代碼。
/*
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node* left;
node* right;
};
vector<int> v;//sorted vector
node* insert(node* root,int data){
if(!root){
root = new node();
root->data = data;
root->left = NULL;
root->right = NULL;
return root;
}
if(root->data > data)
root->left = insert(root->left , data);
else
root->right = insert(root->right , data);
return root;
}
void inOrder(node* root){
if(!root)
return;
inOrder(root->left);
v.push_back(root->data);
//cout<<root->data<<" ";
inOrder(root->right);
}
int main() {
int t;
cin>>t;
while(t--){
node* root = NULL;
int n,el;
cin>>n;
for(int i=0;i<n;i++){
cin>>el;
root = insert(root,el);
}
int k;
cin>>k;
inOrder(root);
cout<<v[k-1]<<endl;
v.clear();
}
return 0;
}
*/ 現在根據我的說法,在最壞的情況下應該是 O(n),但我不確定。 此代碼給了我一個“TLE”。 幫我修復這段代碼。 這可能是我第一次獲得通過 BST 解決問題的直覺,所以我只想通過這種方法來完成這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.