230. Kth Smallest Element in a BST
来源:互联网 发布:phantom无人机控制软件 编辑:程序博客网 时间:2024/05/20 07:53
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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public int kthSmallest(TreeNode root, int k) { List<Integer> res = new ArrayList<>(); inOrder(res, root, k); return res.size() >= k ? res.get(k - 1) : 0; } private void inOrder(List<Integer> res, TreeNode root, int k) { if (root == null || res.size() >= k) return; inOrder(res, root.left, k); res.add(root.val); inOrder(res, root.right, k); }}
阅读全文
0 0
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- [笔记]Student-Class
- HDU 1719 Friend (思路题)公式推导变形
- 基于AI神经引擎的Face ID,真能让人放心吗?
- java.lang.NoClassDefFoundError: javax/servlet/ServletInputStream
- iOS透明导航栏的平滑过渡(进阶版)
- 230. Kth Smallest Element in a BST
- source insight安装破解
- Android自定义view
- 开头为0的md5值总结
- Redis主从架构
- 关于转换内容
- dedecms绑定畅言账号
- 用C++和EasyX图形库编写一个简单的打砖块游戏(下)
- 新手上路之eclipse中jQuery插件及其他好用插件的安装