题解 | #二叉搜索树的第k个节点#

二叉搜索树的第k个节点

https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param proot TreeNode类 
     * @param k int整型 
     * @return int整型
     */
     void Iord(TreeNode* proot,set<int>& tree)
     {
        if(proot==nullptr)
        {
            return;
        }

        Iord(proot->left,tree);
        tree.insert(proot->val);
        Iord(proot->right,tree);
     }
    int KthNode(TreeNode* proot, int k) {
        // write code here
        if(proot==nullptr || k<=0)
        {
            return -1;
        }
        set<int> tree;
        Iord(proot,tree);
        auto it=tree.begin();
        if(k>tree.size())
        {
            return -1;
        }
        while(--k)
        {
            it++;
        }
        return *it;
        
    }
};

全部评论

相关推荐

明天不下雨了:这个项目 这个简历 这个模板 莫不是一个开源的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务