您的位置:首页 > 其它

LeetCode[230] Kth Smallest Element in a BST

2016-09-24 16:59 232 查看
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?
利用中序遍历的思想,用一个变量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) { };
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 递归 二叉树