生成二叉查找树 中序遍历 输出结果 C++实现

本文介绍了一种使用C++编程语言构建二叉排序树的方法。通过递归地插入节点并进行中根遍历来验证二叉排序树的正确性。文章提供了一个完整的示例程序,演示了如何从用户输入创建二叉排序树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

依次输入表(30, 15, 28, 20, 24, 10, 12, 68, 35, 50, 46, 55)中的元素,生成一棵二叉排序数,

要求:编程构建一个二叉排序数,并中根遍历验证上述结果。

#include <stdio.h>
#include <iostream>
using namespace std;

#define size 20
typedef int Elemtype;

/*二叉排序树的二叉链表存储结构*/
typedef struct BTNode {
	Elemtype key;
	struct BTNode *lchild, *rchild;
}*BSTree;

/*二叉排序树的插入*/
BSTree InsertNode(BSTree T, BTNode *s) {
	if (T == NULL)
		return T = s;
	if (s->key < T->key)
		T->lchild = InsertNode(T->lchild, s);
	if (s->key > T->key)
		T->rchild = InsertNode(T->rchild, s);
	return T;
}
/*二叉排序树的创建*/
BSTree Create(BSTree T) {
	BSTree s = NULL;

	int key=0;
	printf("Please enter keywords,end with -1!\n");
	while (1) {
		scanf("%d", &key);
		if (key == -1)
			break;
		s = new BTNode;
		s->key = key;
		s->lchild = s->rchild = NULL;
		T = InsertNode(T, s);		
	}
	return T;
}

void print(BSTree T) {
	if (T == NULL)
		return;
	print(T->lchild);
	printf("%d ", T->key);
	print(T->rchild);
	return;
}

int main()
{
	BSTree T = NULL;
	T=Create(T);
	print(T);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值