您的位置:首页 > 其它

Kth Smallest Element in a BST

2016-02-28 22:43 393 查看
题目:

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.

cpp:

方法一:递归

class Solution {
public:
int kthSmallest(TreeNode* root,int k){
int result;
inOrder(root,k,result);
return result;
}

int n =0;
void inOrder(TreeNode* root,int kth,int& kthVal){
if(!root ) return;
inOrder(root->left,kth,kthVal);
n = n + 1;
if(n == kth) {
kthVal = root->val;
return;
}
inOrder(root->right,kth,kthVal);
}

};


方法2:栈

class Solution{
public:
int kthSmallest(TreeNode* root,int k){
stack<TreeNode*> stack;
int result;
TreeNode *cur = root;
while(!stack.empty() || cur){
if(cur){
stack.push(cur);
cur = cur->left;
}else{
TreeNode* temp = stack.top();
stack.pop();
k--;
if(k==0) {
result = temp->val;
return result;
}
cur = temp->right;
}
}

return result;
}

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