剑指offer54. 二叉搜索树的第k大个节点 P269
题目:给定一棵二叉搜索树,请找出其中的第k大的结点。
中序遍历BST就是有序数列
const BinaryTreeNode* KthNode(const BinaryTreeNode* pRoot, unsigned int k) // 主调函数
{
if(pRoot == nullptr || k == 0)
return nullptr;
return inorder(pRoot, k);
}
// 中序模板
const BinaryTreeNode* inorder (const BinaryTreeNode* root, unsigned int& k)
{
if (root == NULL) return NULL;
BinaryTreeNode* resu = NULL;
resu = inorder(root->left, k);
if (k == 1)
resu = root; //真正赋值的地方只有这
k--;
if(k > 0)
resu = inorder(root->right, k);
return resu;
}