1. 程式人生 > >劍指offer-二叉搜尋樹中的第k個結點

劍指offer-二叉搜尋樹中的第k個結點

題目:

給定一顆二叉搜尋樹,請找出其中的第k大的結點。

二叉搜尋樹的中序遍歷是數值遞增排序的,因此只需要中序遍歷二叉搜尋樹,就可找到第k大的結點。

struct BinaryTree
{
    int data;
    BinaryTree *left;
    BinaryTree *right;
};

//二叉搜尋樹的第K個結點

BinaryTree *KthNode(BinaryTree *pRoot,unsigned int k)
{
    if(pRoot==NULL||k==o)
        return pRoot;
    return KthNodeCore(pRoot,k)
}
BinaryTree * KthNodeCore(BinaryTree *pRoot,unsigned int &k)
{
    BinaryTree *target=NULL;
    
    if(pRoot->left!=NULL)
        target=KthNodeCore(pRoot->left,k);
    if(target==NULL)
    {
        if(k==1)
            target=pRoot;
        k--;
    }
    if(target==NULL&&pRoot->right!=NULL)
        target=KthNodeCore(pRoot->right,k);
    return target;
}