寻找二叉树的第k大节点

来源:互联网 发布:数据制作分析报表 编辑:程序博客网 时间:2024/05/17 03:25

需求:
给定一棵二叉树,求出第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);}