LeetCode[230] Kth Smallest Element in a BST
2016-09-24 16:59
232 查看
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?
利用中序遍历的思想,用一个变量count记录遍历的节点个数,注意不要用static,因为如果 class A 有一个static变量x, 执行 A a; A b; 时,x只会被初始化一次,b的x得不到想要的初值,而测试用例通常有好多个
/**
* 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 count;
int kthSmallest(TreeNode* root, int k) {
int result = 0;
if (root->left != NULL && count < k)
result = kthSmallest(root->left, k);
count++;
if (count == k)
result = root->val;
if (root->right != NULL && count < k)
result = kthSmallest(root->right, k);
return result;
}
Solution(): count(0) { };
};
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?
利用中序遍历的思想,用一个变量count记录遍历的节点个数,注意不要用static,因为如果 class A 有一个static变量x, 执行 A a; A b; 时,x只会被初始化一次,b的x得不到想要的初值,而测试用例通常有好多个
/**
* 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 count;
int kthSmallest(TreeNode* root, int k) {
int result = 0;
if (root->left != NULL && count < k)
result = kthSmallest(root->left, k);
count++;
if (count == k)
result = root->val;
if (root->right != NULL && count < k)
result = kthSmallest(root->right, k);
return result;
}
Solution(): count(0) { };
};
相关文章推荐
- Leetcode230 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
- leetcode230---Kth Smallest Element in a BST(BST中寻找第K小)
- 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
- LeetCode230:Kth Smallest Element in a BST
- [Leetcode 230, Medium] Kth Smallest Element in a BST
- LeetCode230 Kth Smallest Element in a BST
- leetcode-230-Kth Smallest Element in a BST
- [leetcode-230]Kth Smallest Element in a BST(java)
- Java for 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 ( JAVA )