Kth Smallest Element in a BST —— Leetcode
来源:互联网 发布:生死时钟软件 编辑:程序博客网 时间:2024/06/11 19:48
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).
如果每次用递归来计算左子树或右子树的结点个数,类似于二分法,但每次计算左子树节点个数会有很多重复开销;如果按照提示,改变TreeNode的存储结构,再添加一个leftCount属性,那么就比较容易计算出结果了。
下面提供了一种用stack来保存节点的方法,思想是将节点入栈,保证从最小节点开始遍历直到找到第k个,时间复杂度是O(k);
/** * 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) { stack<TreeNode *> st; TreeNode* p = root; while(p || !st.empty()) { while(p) { st.push(p); p = p->left; } p = st.top(); if(--k == 0) { return p->val; } st.pop(); p = p->right; } }};
0 0
- Kth Smallest Element in a BST —— Leetcode
- #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
- 计划策略-20-订货型生产
- 【TsinsenA1309】黑白染色题解
- iOS 常用到的打电话webview
- 微信第三方平台定时接收component_verify_ticket
- new/delete 和malloc/free 的区别一般汇总
- Kth Smallest Element in a BST —— Leetcode
- Leetccode String to Integer (atoi) 字符串转数字
- js的本地存储localstorge
- INSTALL_FAILED_UPDATE_INCOMPATIBLE的另外一种解决办法
- UI03_UIViewController
- 最少的拦截系统
- uCOS-II移植到51单片机任务切换压栈和出栈的操作
- Oracle中的视图理解
- mongodb 自定义函数—自增长id