[算法分析与设计] leetcode 每周一题: Kth Smallest Element in a BST

来源:互联网 发布:淘宝网店如何转让 编辑:程序博客网 时间:2024/06/08 12:28

题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/

题目:

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Credits:
Special thanks to @ts for adding this problem and creating all test cases.



思路:

维护一个动态数组,每次深搜树时,压入当前节点值,同时排序,如果数组大小大于K,则弹出最后一个,维持数组大小为K的状态,最后返回数组最后一个元素


代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> items;    void findKthSmallest(TreeNode* root, int k) {        if(root == nullptr) return ;        items.push_back(root->val);        sort(items.begin(),items.end());        if(items.size() > k) {                        items.pop_back();        }        findKthSmallest(root->left,k);        findKthSmallest(root->right,k);    }    int kthSmallest(TreeNode* root, int k) {            findKthSmallest(root, k);        int last = items.back();        return last;    }};


原创粉丝点击