求二叉排序树的第k个节点

记录下自己愚蠢的一天
首先题目一看都能想到要用中序遍历打方法

int index=0;
TreeNode* KthNode(TreeNode* root, int k)
{
    if(root != NULL)
    { //中序遍历寻找第k个
     KthNode(root->left,k);
        index++;
        if(index == k)
      return root;
        KthNode(root->right,k);
    }
    return NULL;
}

这是我一开始以为没问题的第一段代码,中序遍历嘛,找到第k个就返回,可是我陷入了一个误区,当index==k时,返回的指针只是其中一个递归函数的返回值,并不是说我们最初的这个函数返回了这个指针!
因为如果我们要找的那个节点是在其递归深度中的某个时候找到的。
要这么理解这个思路,对于根节点root,在其左子树中如果找到第k大的节点,则输出该节点,否则判断它自己是不是第k大的节点,然后递归右子树。
代码如下:

int index=0;
    TreeNode* KthNode(TreeNode* root, int k)
    {
        if(root != NULL)
        { //中序遍历寻找第k个
            TreeNode* node = KthNode(root->left,k);
            if(node != NULL)//找到该节点了
                return node;
            index++;
            if(index == k)
                return root;
            node = KthNode(root->right,k);
            if(node != NULL)//找到该节点
                return node;
        }
        //没有找到就返回null
        return NULL;
    }

猜你喜欢

转载自blog.csdn.net/kellen_f/article/details/79174340
今日推荐