LeetCode 230 Kth Smallest Element in a BST
来源:互联网 发布:淘宝浏览单佣金3 3 3 编辑:程序博客网 时间:2024/05/22 21:21
题目描述
Given a binary search tree, write a function kth Smallest 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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node’s structure?
- The optimal runtime complexity is O(height of BST).
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析
因为是BST,那么中序遍历即得到从小到大的序列。中序遍历,到第k次即可。
代码
public int kthSmallest(TreeNode root, int k) { if (root == null) { return -1; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; while (p != null || !stack.isEmpty()) { while (p != null) { stack.push(p); p = p.left; } if (!stack.isEmpty()) { p = stack.pop(); if (--k == 0) { return p.val; } p = p.right; } } return 0; }
2 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
- centos7.1的java环境服务器
- Ubantu下安装OpenCV
- 根据目前业务优化的新架构
- Java IO流详尽解析
- jquery实现form表单的submit和reset
- LeetCode 230 Kth Smallest Element in a BST
- oracle分页查询原理
- sd卡启动分区的制作--使用fdisk 工具
- PE总结10---PE文件结构之导入表 (IMAGE_IMPORT_DESCRIPTOR)
- 解决中文乱码问题和懒加载问题的两款过滤器
- notify 和 notifyall 的区别,yield 和 wait,sleep的区别
- android cookie管理,解决网页访问不了的问题
- C++运算符重载
- ReentrantReadWriteLock读写锁的使用