您的位置:首页 > 其它

LeetCode 230. Kth Smallest Element in a BST

2016-04-22 02:53 501 查看
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.

Just read the question carefully, then, there is no problem. BST.....

void inorder(TreeNode* root, int &res, int &idx,int k){
if (root==NULL || idx>=k) return;
inorder(root->left,res,idx,k);
idx++;
if (idx ==k ) res = root->val;
inorder(root->right,res,idx,k);
}

int kthSmallest(TreeNode* root, int k) {
int res;
int idx=0;
inorder(root,res,idx,k);
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: