Kth Smallest Element in a BST
来源:互联网 发布:网络舆情监测 编辑:程序博客网 时间:2024/05/20 23:30
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?
public class Solution { public int kthSmallest(TreeNode root, int k) { int count = countNodes(root.left); if (k <= count) { return kthSmallest(root.left, k); } else if (k > count + 1) { return kthSmallest(root.right, k-1-count); // 1 is counted as current node } return root.val; } public int countNodes(TreeNode n) { if (n == null) return 0; return 1 + countNodes(n.left) + countNodes(n.right); }}
0 0
- #leetcode#Kth Smallest Element in a BST
- 230.Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- 多值域相加
- 栈的链式存储实现
- UIlabel自适应高度和UITableViewCell自适应高度
- Android测试二----InstrumentationTestRunner运行测试用例机制
- JDBC及eclipse连接数据库
- Kth Smallest Element in a BST
- hdu 1558 并查集+线段相交
- 2015 深圳杯数模 B: DNA分子序列- RK算法
- 如何判断链表中是否有环
- strong,weak, retain, assign的区别
- sonarQube代码质量管理
- 【线段树】【NOI 1999】【cogs 284】内存分配
- visual studio2010已停止工作。。。
- 像素是什么意思?一个像素有多大? 告诉你像素和分辨率的关系!