//建立二叉排序树
#include<stdio.h>
#include<iostream>
#include<stack>
#include<string.h>
#include <queue>
using namespace std;
char before[100], in[100];
struct Node
{
Node* lchild;
Node* rchild;
int c; //保存数字
}Tree[110];
int loc; //静态数组中被使用元素的个数
Node* create() //申请未使用的结点
{
Tree[loc].lchild = Tree[loc].rchild = NULL;
return &Tree[loc++];
}
void postOrder(Node *T) //后序遍历
{
if(T -> lchild != NULL){
postOrder(T -> lchild);
}
if(T -> rchild != NULL){
postOrder(T -> rchild);
}
printf("%d ", T ->c ) ;
}
void inOrder(Node *T) //中序遍历
{
if(T -> lchild != NULL){
inOrder(T -> lchild);
}
printf("%d ", T ->c ) ;
if(T -> rchild != NULL){
inOrder(T -> rchild);
}
}
void preOrder(Node *T) //前序遍历
{
printf("%d ", T ->c ) ;
if(T -> lchild != NULL){
preOrder(T -> lchild);
}
if(T -> rchild != NULL){
preOrder(T -> rchild);
}
}
Node *Insert(Node *T, int x) //插入数字 X
{
if(T == NULL){ //若当前树为空
T = create(); //申请结点
T -> c = x; //数字直接插入其根结点
return T; //返回其根节点的指针
}else if( x < T -> c){ //若x小于根节点的数值
T -> lchild = Insert(T -> lchild, x); //插入到左子树上
}else if(x > T -> c){
T -> rchild = Insert(T -> rchild, x); //否则插入到右子树上 (根据题意 如果值相同的 直接忽略即可
}
return T; //返回根节点指针
}
int main(){
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n;
while(scanf("%d", &n) != EOF){
loc = 0;
Node *T = NULL; //二叉排序树树根结点为空
for(int i = 0; i < n; i++){
int x;
scanf("%d", &x);
T = Insert(T, x);
}
preOrder(T);
printf("\n");
inOrder(T);
printf("\n");
postOrder(T);
printf("\n");
}
return 0;
}
建立二叉排序树
最新推荐文章于 2025-10-19 23:47:57 发布
本文介绍了一种二叉排序树的数据结构,并通过C++代码实现了该结构的创建及三种基本遍历方法:前序遍历、中序遍历和后序遍历。文章提供了完整的代码示例,包括节点的创建、插入操作等关键步骤。
259

被折叠的 条评论
为什么被折叠?



