您的位置:首页 > 其它

二叉搜索树的第k个节点

2017-03-28 09:39 232 查看
题目描述:给定一颗二叉搜索树,请找出其中的第k大的节点。

只需中序遍历一颗二叉搜索树,就很容易找出它的第k大节点

非递归方法:

class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot==nullptr || k<=0)
return nullptr;
int cnt=0;
stack<TreeNode*>s;
TreeNode* p = pRoot;
while(p != nullptr || !s.empty())
{
while(p!=nullptr)
{
s.push(p);
p=p->left;
}
TreeNode* pNode=s.top();
s.pop();
if(++cnt==k)
return pNode;
p=pNode->right;
}
return nullptr;
}

};递归方法:
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot==nullptr)
return nullptr;
return KthNodeCore(pRoot,k);
}
TreeNode*KthNodeCore(TreeNode* pRoot, int &k)
{
TreeNode* pNode=nullptr;
if(pRoot->left != nullptr)
pNode=KthNodeCore(pRoot->left, k);
if(pNode==nullptr)
{
if(k==1)
pNode=pRoot;
k--;

}
if(pNode == NULL && pRoot->right != nullptr)
pNode=KthNodeCore(pRoot->right, k);
return pNode;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: