给定一棵二叉搜索树,请找出其中第k大的结点。
本文有关二叉搜索树节点结构体的定义和二叉搜索树创建算法如下:、
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
typedef struct BSTreeNode{
DataType key;
struct BSTreeNode *left;
struct BSTreeNode *right;
}BSTreeNode;
//创建二叉搜索树
int BSTreeInsert2(BSTreeNode **root, DataType key)
{
if (*root == NULL)
{
BSTreeNode *node = (BSTreeNode *)malloc(sizeof(BSTreeNode));
node->key = key;
node->left = NULL;
node->right = NULL;
*root = node;
return 1;
}
if (key == (*root)->key)
{
return 0;
}
else if (key < (*root)->key)
{
//这种做法不对,改变的只是栈上临时变量的值
//BSTreeNode *child=(*root)-left;
//return BSTreeInsert2(&child,key);
return BSTreeInsert2(&(*root)->left, key);
}
else
{
return BSTreeInsert2(&(*root)->right, key);
}
}
按照中序遍历的顺序遍历一棵二叉搜索树,则它的遍历的数值是从小到大依次递增的。中序遍历一棵二叉树,定义一个全局变量count,每当二叉搜索树遍历完一个结点时count加1。当count==k时,说明已经找到第k大个结点,打印其key值即可。
代码如下:
static int count = 0;
void KthNode2(BSTreeNode *root, int k)
{
if (root == NULL || k == 0)
{
return;
}
KthNode2(root->left, k);
count++;
if (count== k)
{
printf("%d", root->key);
}
KthNode2(root->right, k);
}