建立二叉排序树

本文介绍了一种二叉排序树的数据结构,并通过C++代码实现了该结构的创建及三种基本遍历方法:前序遍历、中序遍历和后序遍历。文章提供了完整的代码示例,包括节点的创建、插入操作等关键步骤。

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

//建立二叉排序树
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值