[算法分析与设计] 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; }};
阅读全文
0 0
- [算法分析与设计] leetcode 每周一题: Kth Smallest Element in a BST
- [算法分析与设计] leetcode 每周一题: 215. Kth Largest Element in an Array
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 测试小白禅道的软件环境搭建基础案例分享
- IIS+PHP上传数据大小限制
- 003
- 机器学习API文档(演示) (一)监督学习
- 数据结构课程设计————内部排序性能分析
- [算法分析与设计] leetcode 每周一题: Kth Smallest Element in a BST
- JavaEE颠覆者:spring-boot实战随书源码
- 封装OkHttp
- 小程序项目复制注意事项个人笔记
- Java-NIO(三):直接缓冲区与非直接缓冲区
- 【Codeforces183D】T-shirt
- 在Eclipse上安装Spring Tool Suite
- 很好看的css3 Loading
- 目标检测方法系列——R-CNN, SPP, Fast R-CNN, Faster R-CNN, YOLO, SSD