[LeetCode]Kth Smallest Element in a BST
来源:互联网 发布:写关于宿舍知乎 编辑:程序博客网 时间:2024/06/05 16:28
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?
题解:使用DFS,BTS的结构是root.left<root<root.right,采用中序遍历,可以得到k小的值。
code:
public class Solution { private int value;private int index;public int kthSmallest(TreeNode root, int k) {index = 0;dfs(root, k);return value;}public void dfs(TreeNode root, int k) {if(root == null)return;dfs(root.left, k);index++;if (index == k) {value = root.val;return;}dfs(root.right, k);}}
0 0
- #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
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- jQuery源码分析之on方法
- Collection集合,数组
- 学生选课系统代码(主界面部分)
- 不用品回収 网站
- (1)ActiveMQ安装配置
- [LeetCode]Kth Smallest Element in a BST
- 深入了解 Dojo 的核心接口
- DASI_3 _CI&HT
- CSS3 Animation transform
- iOS弹解盘时 控制界面滚动的封装类
- Struts2的getServletContext().getRealPath("/WEB-INF")报空指针异常问题
- 关于用了一天时间在虚拟机下共享网络的问题说明
- shell 脚本学习七
- opencv2-3生成标定用的方格图