[leetcode][BST] Kth Smallest Element in a BST
来源:互联网 发布:奢侈品销售 知乎 编辑:程序博客网 时间:2024/05/16 15:35
题目:
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?
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).
基本解法:O(n),其中n为BST的节点个数
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:int kthSmallest(TreeNode* root, int k) {if (NULL == root || k < 1) return -1;//非法输入,应抛出异常的stack<TreeNode *> sta;TreeNode *p = root;int cnt = 0;while (p != NULL || !sta.empty()){while (p != NULL){//一路向左sta.push(p);p = p->left;}//visitTreeNode *q = sta.top();sta.pop();if (++cnt == k) return q->val;p = q->right;}}};
优化解法:
思路:在节点数据结构中增加一个表示在BST中该节点左边的节点个数的int型成员lCnt
插入:在查找节点插入位置的过程中,如果该节点应该放在当前节点的左边,则当前节点的lCnt加1,找到该节点的合适位置时,该节点的lCnt为0
删除:在查找删除节点的过程中,如果该节点值小于当前节点值,则当前节点的lCnt减1
查找:如果k小于当前节点的lCnt,到当前节点的左边继续查找;否则到当前节点的右边继续查找k=k-cur->lCnt-1
实现:待续
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
- python 自定义异常
- 织梦实现一个标签调用不同的文件
- Objective-C编码规范:26个方面解决iOS开发问题
- java.net.SocketException: socket failed: EACCES (Permission denied)联网权限已经设置了还是报错的两个原因及解决方案
- SUNWprivate_1.1 not defined in file libjvm.so
- [leetcode][BST] Kth Smallest Element in a BST
- Linux内核软RPS实现网络接收软中断的负载均衡分发
- 页面与后台传递中文乱码问题(java乱码)
- HDU 2602(Bone Collector)基础0-1背包问题
- 事件声明与赋值
- [Leetcode题解]001 Two Sum
- 网络优化经历
- Eclipse 实用快捷键
- iOS开发工具-网络封包分析工具Charles