[LeetCode] Algorithms-45. 230. Kth Smallest Element in a BST
2018-01-13 20:02
246 查看
描述:
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?
思路:
对于BST的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 *> par; TreeNode *cur = root; int tem = 0; while(cur || !par.empty()) { while(cur) { par.push(cur); cur = cur->left; } cur = par.top(); if(--k == 0) return cur->val; par.pop(); cur = cur->right; } } };
相关文章推荐
- LeetCode 230. Kth Smallest Element in a BST
- 【LeetCode】230. Kth Smallest Element in a BST
- [Leetcode] 230. Kth Smallest Element in a BST
- [Leetcode] 230. Kth Smallest Element in a BST 解题报告
- LeetCode *** 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- <LeetCode OJ> 230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST
- 【LeetCode】 230. Kth Smallest Element in a BST
- [LeetCode]230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST(二叉搜索树中的第K个元素)
- leetcode 230. Kth Smallest Element in a BST
- 【LeetCode】230. Kth Smallest Element in a BST (2 solutions)
- leetcode-230. Kth Smallest Element in a BST
- [leetcode]230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- leetcode_middle_26_230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST