• LeetCode230二叉搜索树中第K小的元素


    题目链接

    https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

    题解

    • 递归解法
    • 根据BST的性质,中序遍历BST得到的结点序列为结点的升序序列,序列中第k个元素就是第k小的元素。
    • 所以可以中序遍历BST生成升序序列,找到第k个元素则停止遍历。
    // Problem: LeetCode 230
    // URL: https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
    // Tags: Tree BST Recursion DFS
    // Difficulty: Medium
    
    #include <vector>
    using namespace std;
    
    struct TreeNode{
        int val;
        TreeNode* left;
        TreeNode* right;
    };
    
    class Solution{
    private:
        vector<int> vals;
        int k;
    public:
        // 中序遍历
        void inorder(TreeNode* root){
            if (root==nullptr) return;
            // 遍历左子树
            inorder(root->left);
            // 剪枝:如果已经遍历到第K个元素,则不用再遍历
            if (this->vals.size() >= this->k) return;
            // 遍历当前根结点
            this->vals.push_back(root->val);
            // 遍历右子树
            inorder(root->right);
        }
    
        // 获取BST中第k小的元素
        int kthSmallest(TreeNode* root, int k) {
            this->k = k;
            // 中序遍历生成元素的升序序列
            inorder(root);
            // 结果为升序序列中的第k个元素,下面的两行代码都可以
            return this->vals[k - 1]; // return this->vals.back();
        }
    };
    

    作者:@臭咸鱼

    转载请注明出处:https://www.cnblogs.com/chouxianyu/

    欢迎讨论和交流!


  • 相关阅读:
    Pandas获取本地csv文件到内存中
    波士顿房价数据集可视化
    tensorflow之数据集调用(波士顿房价数据集)
    查单词
    censoring
    字符串大师
    Parity game
    前缀和
    String
    Seek the Name, Seek the Fame
  • 原文地址:https://www.cnblogs.com/chouxianyu/p/13414462.html
Copyright © 2020-2023  润新知