230. Kth Smallest Element in a BST
2018-02-02 08:49
302 查看
Given a binary search tree, write a function
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?
kthSmallestto 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?
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; } } };
int kthSmallest(TreeNode* root, int& k) { if (root) { int x = kthSmallest(root->left, k); return !k ? x : !--k ? root->val : kthSmallest(root->right, k); } }
相关文章推荐
- 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
- 230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- LeetCode#230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST 解题报告
- 230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历是有序序列
- 230. Kth Smallest Element in a BST
- leecode 解题总结:230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST
- leetcode-230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST | 二叉排序树中查找第K小的数
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST