尋找二叉樹的第k大節點
阿新 • • 發佈:2019-02-15
需求:
給定一棵二叉樹,求出第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);
}