需求:
给定一棵二叉树,求出第k大的节点。
根据二叉树的中序遍历中序遍历即可找到第k大的节点。
实现:
节点定义:
typedef struct node{
int data;
struct node *left;
struct node *right;
}BTNode;
BTNode* searchTagCore(BTNode *root, int* k){
BTNode *tag = NULL;
if (root->left){
tag = searchTagCore(root->left, k);
}
if (!tag){
if (1 == *k){
//说明当前节点就是目标值
tag = root;
}
(*k)--;
}
if (!tag&&root->right){
tag = searchTagCore(root->right,k);
}
return tag;
}
BTNode* searchTag(BTNode *root, int k){
if (!root || !k){
return NULL;
}
return searchTagCore(root, &k);
}