题解 | #c++ 遇事不决哈希表,二次排序#
二叉搜索树的第k个结点
http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
map<TreeNode*,int> result;
/* 对哈希表按照value 排序方式1 外部排序函数
bool cmp_by_value( pair<TreeNode*,int> x,pair<TreeNode*,int> y){
return x.second<y.second;};
*/
class Solution {
public:
void dfsserch(TreeNode* node, void anyfunction(TreeNode* p)){
if(node==nullptr){
return;
}else{
anyfunction(node);
dfsserch(node->left, anyfunction);
dfsserch(node->right, anyfunction);
}
}
static void function(TreeNode* p){
result.insert({p,p->val});
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(k == 0 || pRoot == nullptr){
return nullptr;
}//方式2 : 降序排序
auto cmpmax = [](const pair<TreeNode*, int> x,const pair<TreeNode*,int> y){
return x.second>y.second;};
//方式2 : 升序排序
auto cmpmin = [](const pair<TreeNode*,int> x,const pair<TreeNode*,int> y){
return x.second<y.second;};
dfsserch(pRoot, function);
vector<pair<TreeNode*,int>> results(result.begin(),result.end());
sort(results.begin(),results.end(),cmpmax);
for(auto x : results){
cout << "value : " << x.second<<",";
}while(--k){
results.pop_back();
}
return results.back().first;
}
};