复制代码
// 面试题54:二叉搜索树的第k个结点
// 题目:给定一棵二叉搜索树,请找出其中的第k大的结点。
#include <iostream>
#include "BinaryTree.h"
const BinaryTreeNode* KthNodeCore(const BinaryTreeNode* pRoot, unsigned int& k);
const BinaryTreeNode* KthNode(const BinaryTreeNode* pRoot, unsigned int k)
{
if (pRoot == nullptr || k == 0)//判断边界
return nullptr;
return KthNodeCore(pRoot, k);
}
const BinaryTreeNode* KthNodeCore(const BinaryTreeNode* pRoot, unsigned int& k)//k必须引用传递啊,不然记不住
{
const BinaryTreeNode* target = nullptr;
if (pRoot->m_pLeft != nullptr)//迭代找出最小点
target = KthNodeCore(pRoot->m_pLeft, k);
if (target == nullptr)//找到最小节点了,并k--,如果k==1,就算是找到了,记下target
{
if (k == 1)
target = pRoot;
k--;
}
if (target == nullptr && pRoot->m_pRight != nullptr)//一旦找到target,就不会继续迭代了,全部返回
target = KthNodeCore(pRoot->m_pRight, k);
return target;
}