leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历
来源:互联网 发布:音频美化软件 编辑:程序博客网 时间:2024/05/17 03:32
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?
考察要点:二叉搜索树BST的中序遍历可以得到一个有序的序列。
所以DFS深度优先遍历遍历即可。
代码如下:
import java.util.ArrayList;/*class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}*//* * 这道题的关键就是BST的中序遍历得到的就是排序好的数组 * 这个是k小元素,我们的得到的是从小到大的元素(优先遍历左结点,然后右结点) * 假如是k大元素,直接邮箱遍历右结点,然后是左结点,同样如此 * * */public class Solution { public int kthSmallest(TreeNode root, int k) { if(root==null || k<=0) return -1; ArrayList<Integer> one=new ArrayList<>(); getKSmall(root,one,k); return one.get(k-1); } public void getKSmall(TreeNode root, ArrayList<Integer> one,int k) { if(root!=null) { getKSmall(root.left, one,k); one.add(root.val); if(one.size()==k) return; getKSmall(root.right, one,k); } }}
下面是C++的做法,就是一个简单的DFS深度优先遍历的应用,
这道题最重要的事情就是要记住BFS二叉搜索树的中序遍历的结果是一个有序序列
代码如下:
#include <iostream>#include <algorithm>#include <vector>#include <set>#include <string>#include <map>using namespace std;/*struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};*/class Solution{public: vector<int> res; int kthSmallest(TreeNode* root, int k) { getAll(root, k); return res[k - 1]; } void getAll(TreeNode* root, int k) { if (root != NULL) { getAll(root->left,k); res.push_back(root->val); if (res.size() == k) return; getAll(root->right,k); } }};
阅读全文
0 0
- leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历
- 230.leetcode Kth Smallest Element in a BST(medium)[二叉搜索树 先序遍历 栈]
- leetcode -- 230. Kth Smallest Element in a BST 【遍历 + 计数】
- LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字
- [leetcode 230]Kth Smallest Element in a BST----求二叉搜索树的第K小值
- Kth Smallest Element in a BST 找二叉搜索树中的第k小的元素
- LeetCode 230. Kth Smallest Element in a BST(二叉搜索树中的第K个元素)
- #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
- 初始化一个mvn工程
- Node.js模块系统
- Qt音乐播放器的实现(未完持续)
- SpringMVC + MyBatis + Mysql + Redis(作为二级缓存) 配置
- 不同浏览器对post上传文件时,文件名的处理方式不同。
- leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历
- linux XShell上传、下载本地文件到linux服务器
- 设置背景透明文字内容不透明方法
- web项目启动后的加载顺序
- Effective STL 39 Make predicates pure functions
- java触发器学习
- ArrayList指单链表分析
- 有关于数据库查询语法中,对时间有要求的方法
- codeforces 461B 树DP