题目描述:
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路:
基于搜索二叉树的中序遍历可以按顺序从小到大遍历到每个节点,因此当通过中序遍历遍历到第k个节点就是第k小的节点。
代码(递归):
class solution
{
public:
TreeNode* result=NULL;
int num=0;
public:
TreeNode* KNode(TreeNode* pRoot,int k)
{
if(pRoot)
{
findK(pRoot);
return result;
}
}
/*需要遍历完所有节点*/
void findK(TreeNode* pRoot)
{
if(!pRoot)
return;
findK(pRoot->left)
num++;
if(num==k)
{
result= pRoot;
}
findK(pRoot->right);
}
}
代码(非递归):
class solution
{
public:
int num=0;
TreeNode* KNode(TreeNode* pRoot,int k)
{
stack<TreeNode*> data;
TreeNode* p=pRoot;
TreeNode* result=NULL;
data.push_back(p);
while(p||!data.empty())
{
if(p)
{
num++;
data.push(p);
/*不用遍历完*/
if(num==k)
{
result=P;
break;
}
p=p->left;
}
else
{
p=data.top();
data.pop();
p=p->right;
}
}
return result;
}
}