您的位置:首页 > 其它

LeetCode:Kth Smallest Element in a BST

2015-08-14 16:24 204 查看
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中序遍历 得到有序序列 以下用的是递归 ,当然也可以用栈

解法一:看leetcode提交记录

/**
* 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 {
private:
int count=0;
int result=0;
public:
int kthSmallest(TreeNode* root, int k) {
if(root==NULL) return 0;
kthSmallest(root->left,k);
if(count<k)
{
count++;
if(count==k)
result=root->val;
}
if(root->right!=NULL)
kthSmallest(root->right,k);
return result;

}

};


代码二:

/**
* 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) {
int count=0;
int result=0;
inorderTraversal(root,count,result,k);
return result;

}
void inorderTraversal(TreeNode *node,int &count,int &result,int &k)
{
if(node==NULL) return;
inorderTraversal(node->left,count,result,k);

if(count<k)
{count++;
if(count==k)
{
result=node->val;
return ;
}
}
inorderTraversal(node->right,count,result,k);
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: