二叉搜索树的第k个结点

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / 3 7 / / 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
 
思路一:
class Solution {
    int count = 0;
public:
    TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
    {
        if(pRoot){ 
                TreeNode *ret = KthNode(pRoot->left, k);
                if(ret) return ret;
                if(++count == k) return pRoot;
                ret = KthNode(pRoot->right,k);
                if(ret) return ret;
        }
        return nullptr;
    }
};

注意:if(ret) return ret; 为了确保在找到(count == k)的时候能逐层返回。

ret为根左右结构中的根时才不为NULL,ret不为NULL,说明在左右的子树的-左根右结构的-根中已经找到!  

 
若上述C++代码没有看懂,可以看如下的思路二Java版本代码。
思路二:
//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
//     所以,按照中序遍历顺序找到第k个结点就是结果。
public class Solution {
   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;
        }
        return null;
    }
}

  

思路三:
class Solution {
public:
    //中序遍历的结果就是有序序列,第K个元素就是vec[K-1]存储的节点指针;
    TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
    {
        if(pRoot==NULL||k<=0) return NULL;
        vector<TreeNode*> vec;
        Inorder(pRoot,vec);
        if(k>vec.size())
            return NULL;
        return vec[k-1];
    }
    //中序遍历,将节点依次压入vector中
    void Inorder(TreeNode* pRoot,vector<TreeNode*>& vec)
    {
        if(pRoot==NULL) return;
        Inorder(pRoot->left,vec);
        vec.push_back(pRoot);
        Inorder(pRoot->right,vec);
    } 
};

  

二叉树基本操作:前序、中序、后序遍历(递归方式)

思路四:没看明白!!!
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    void inorder(TreeNode* root,TreeNode* &ans) {
        if(root) {
            inorder(root->left,ans);
            count--;
            if(!count) ans=root;
            inorder(root->right,ans);
        }
    }
    
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(!pRoot ||k<1) return NULL;
        TreeNode * ans=NULL;
        count=k;
        inorder(pRoot,ans);
        return ans;
    }
private:
    int count;

    
};

  

拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
原文地址:https://www.cnblogs.com/dd2hm/p/7488360.html