面试题54:二叉搜索树的第k大节点

题目描述

求二叉搜索树的第k大节点?

算法分析

二叉搜索(排序,查找)树,左子树<根<右子树。那么中序遍历二叉搜索树则为从小到大的序列。
中序遍历一遍二叉搜索树,得到节点个数n,然后第k大节点就是第n-k+1小的节点.

完整代码

cpp 复制代码
#include "二叉排序树.h"

//统计树的节点个数
int CountNode(BSTree T)
{
	if (T == NULL)
		return 0;
	return CountNode(T->lchild) + 1 + CountNode(T->rchild);
}

//利用中序遍历算法找第i个节点
BSTNode* IthNode(BSTree T, int *pi)
{
	BSTNode* target = NULL;
	if (T->lchild != NULL) //处理左子树
		target = IthNode(T->lchild,pi);
	if (target == NULL) //处理根节点
	{
		if (*pi == 1)//就是当前的根
			target = T;
		--*pi;
	}
	if (target==NULL && T->rchild != NULL) //处理右子树
		target = IthNode(T->rchild, pi);

	return target;
}

//得到二叉排序树第k大的节点(需要转为第n-k+1小的节点)
BSTNode* KthNode(BSTree T, unsigned int k)
{
	//通过中序遍历算法,计算节点个数
	int n = CountNode(T);
	if (k <= 0 || k > (unsigned int)n)//参数非法
		return NULL;
	int i = n - k + 1;//把第k大转为第i小

	return IthNode(T,&i);
}

int main()
{
	BSTree T;
	printf("请输入插入的数据序列,-1表示结束:");
	CreateBST(&T);树1:45 24 53 12 37 93 -1   树2:12 24 37 45 53 93 24 -1

	printf("中序遍历这棵二叉排序树(有序):");      
	InOrder(T);      
	printf("\n");      

	int k = 1;      
	//int k = 3;      
	BSTNode* p = KthNode(T,k);      
	if (p == NULL)      
		printf("没有找到\n");      
	else      
		printf("第%d大的数字为:%d\n",k,p->data.key);      

	return 0;      
}

本篇完!

相关推荐
橘子汽水16823 分钟前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode
LuminousCPP33 分钟前
数据结构-排序(三):快速排序进阶|挖坑法、双指针交换与手动栈非递归实现
c语言·数据结构·笔记·算法·排序算法
数据知道1 小时前
国密算法实战——SM2/SM3/SM4 在国产系统中的应用
网络·算法·安全·网络安全·密码学·哈希算法
zander2582 小时前
LeetCode 128. 最长连续序列
数据结构·算法
linx2952 小时前
单元四 · 对称认知·上:内存与指针
c语言·开发语言·数据结构·嵌入式硬件·算法
午彦琳3 小时前
2026.9.11
数据结构·python·算法
302wanger4 小时前
蛋炒饭周刊 · 第 1 期(2026-09-07至2026-09-11)
算法
shehuiyuelaiyuehao4 小时前
算法43,外观数列,模拟算法+双指针
java·算法
alphaTao4 小时前
LeetCode 每日一题 2026/9/7-2026/9/13
算法·leetcode