c_cpp 找到BST的第k个最小节点
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 找到BST的第k个最小节点相关的知识,希望对你有一定的参考价值。
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int v) :val(v) {}
};
// ================================================================
// solution 1, good, easy to understand
void find_kth_smallest(TreeNode *root, TreeNode* &res, int &k) {
if(!root || k < 0) return ;
find_kth_smallest(root->left, res, k);
k--;
if(k == 0) {
res = root;
return;
}
find_kth_smallest(root->right, res, k);
}
// ================================================================
// solution 2, also good.
int getNodeNum(TreeNode *root) {
if(!root) return 0;
return 1 + getNodeNum(root->left) + getNodeNum(root->right);
}
void get_kth_smallest(TreeNode *root, TreeNode *&res, int k) { // not &k
if(!root || k<0) return;
int size_left = getNodeNum(root->left);
if(size_left == k-1) {
res = root;
return;
}
else if(size_left < k-1)
get_kth_smallest(root->right, res, k-size_left-1); // don't forget -1
else
get_kth_smallest(root->left, res, k);
}
// ================================================================
// a concise version, 4/30/2014, hard to understand!
treenode* kth(treenode *r, int &k) {
if(!r || k < 0) return NULL;
kth(r->left, k);
if(k == 1) return r;
return kth(r->right, --k); // why return the right subtree's result?
}
// ================================================================
// or maybe this version? not tested!
void findKth(TreeNode *root, TreeNode* &res, int &k, int K) {
if(!root || k >= K) return;
findKth(root->left, res, k, K);
if(k+1 == K) {
res = root;
return;
}
findKth(root->right, res, k+1, K);
}
// ================================================================
int main()
{
TreeNode *r = new TreeNode(3);
r->left = new TreeNode(1);
r->right = new TreeNode(4);
int k = 1;
TreeNode *res;
find_kth_smallest(r, res, k);
cout << res->val;
return 0;
}
以上是关于c_cpp 找到BST的第k个最小节点的主要内容,如果未能解决你的问题,请参考以下文章
以最优方式在二叉搜索树中找到第 k 个最小元素
剑指offer二叉搜索树的第k个结点
c_cpp 插入节点在bst,BST中
c_cpp BST查找最小值和最大值
二叉排序树(BST)
230. Kth Smallest Element in a BST