题目描述:
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
思路:
由于是二叉搜索树,所以是中序遍历的第K个节点。
代码:
解法一(来自剑指offer):
/**
* 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) {
return mid(root,k)->val;
}
TreeNode* mid(TreeNode* root, int &k){
TreeNode * target = NULL;
if(root->left != NULL){
target = mid(root->left,k);
}
if(target == NULL){
if(k == 1){
target = root;
}
k--;
}
if(target == NULL && root->right != NULL)
target = mid(root->right,k);
return target;
}
};
解法二:
基于循环来中序遍历二叉树。
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int temp;
if(!root)
return -1;
stack<TreeNode*> s;
int count = 0;
TreeNode* p = root;
while(p||!s.empty()){
while(p){
s.push(p);
p = p->left;
}
p = s.top();s.pop();
if(++count==k) return p->val;
p = p->right;
}
return -1;
}
};
原文链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/comments/