**题目:**给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
**思路:**中序遍历二叉树,遍历的过程中加入一个计数器,当到达第k个时,输出即可。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
int count;
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if (pRoot==nullptr||k <= 0) return nullptr;
TreeNode* v=nullptr;
count = k;
DFS(pRoot, v);
return v;
}
void DFS(TreeNode* root, TreeNode* &tmp)
{
if (root)
{
DFS(root->left, tmp);
count--;
if (!count) tmp = root;
DFS(root->right, tmp);
}
}
};