您的位置:首页 > Web前端

剑指offer--62.二叉搜索树的第k个结点

2019-02-28 22:30 239 查看

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4

时间限制:1秒 空间限制:32768K 热度指数:157331

思路

中序遍历,递归

/*
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)
{
if(pRoot!=NULL)//当结点非空
{
TreeNode* ans =KthNode(pRoot->left, k);//访问左子树
if(ans!=NULL)//若不为NULL,则说明已经找到
return ans;
++count;        //计数
if(count==k)
return pRoot;
ans =KthNode(pRoot->right, k);//访问右子树
if(ans!=NULL)//若不为NULL,则说明已经找到
return ans;
}
//左右子树不包括第K个结点时,返回NULL
return NULL;

}
private:
int count=0;//计数

};

非递归

/*
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)
{
if(k==0||pRoot==NULL)
return NULL;
stack<TreeNode*> p;
int cnt=0;//计数器
TreeNode* t=pRoot;
while(t||!p.empty())
{
if(t)
//当有左子树的时候,不断将左子树入栈
{
p.push(t);
t=t->left;
}
else //没有左子树时或当前结点为空时,返回父母结点,访问其右子树
{
//自增和判断是否到达k,即中序遍历中的访问结点内容
++cnt;
t=p.top();
p.pop();
if(cnt==k)
return t;

//中序访问右子树
t=t->right;
}
}
return NULL;
}

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