题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
解法一:
中序遍历递归
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
TreeNode* p = NULL;
int count=0;
Inorder(pRoot, p, count, k);
return p;
}
void Inorder(TreeNode* &pRoot, TreeNode* &p , int &count, int &k)
{
if(pRoot==NULL || count>k)
return ;
Inorder(pRoot->left, p, count, k);
count++;
if(count==k)
p = pRoot;
Inorder(pRoot->right, p, count, k);
}
};
解法二:
中序遍历非递归
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
return Inorder(pRoot, k);
}
TreeNode* Inorder(TreeNode* &pRoot, int &k)
{
int count = 0;
TreeNode* p = pRoot;
stack<TreeNode* >st;
while(!st.empty() || p!=NULL)
{
while(p)
{
st.push(p);
p = p->left;;
}
p = st.top();
count++;
if(count==k)
return p;
st.pop();
p = p->right;
}
return NULL;
}
};