面试题54:二叉搜索树的第k个结点
题目:给定一棵二叉搜索树,请找出其中的第k大的结点。
#include<iostream>
using namespace std;
struct BinaryTreeNode{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
// 二叉搜索树的中序遍历思想
BinaryTreeNode KthNodeCore(BinaryTreeNode* pRoot, unsigned int& k){
BinaryTreeNode* target=NULL;
if(pRoot->left!=NULL) target=KthNodeCore(pRoot->left, k);
if(target==NULL){
if(k==1) target=pRoot;
k--;
}
if(target==NULL && pRoot->right!=NULL) target=KthNodeCore(pRoot->right, k);
return target;
}
BinaryTreeNode* KthNode(BinaryTreeNode* pRoot, unsigned int k){
if(pRoot==NULL || k==0) return NULL;
return KthNodeCore(pRoot, k);
}
int main() {
return 0;
}