排序二叉树的遍历

本文介绍如何根据给定的整数序列构建二叉排序树,并实现前序、中序和后序遍历。首先通过比较每个整数与根节点确定其在树中的位置,然后递归地构建左右子树。最后,通过三种不同的遍历方式输出树的结构。

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

给定一系列整数,建立二叉排序树,输出前序、中序和后序遍历结果

#include<stdio.h>
#include<string.h>

struct Node{
Node *ltre;
Node *rtre;
int w;
}buf[50];
int a[30];
int loc,n;

Node *create(){
buf[loc].ltre=buf[loc].rtre=NULL;
return &buf[loc++];
}

void pre(Node *t){
printf("%d ",t->w);
if(t->ltre!=NULL){
    pre(t->ltre);
}
if(t->rtre!=NULL){
    pre(t->rtre);
}
}

void mid(Node *t){
if(t->ltre!=NULL){
    mid(t->ltre);
}
printf("%d ",t->w);
if(t->rtre!=NULL){
    mid(t->rtre);
}
}

void aft(Node *t){
if(t->ltre!=NULL){
    aft(t->ltre);
}
if(t->rtre!=NULL){
    aft(t->rtre);
}
printf("%d ",t->w);
}



void build(int x,Node *t){

if(x>t->w){

    if(t->rtre==NULL){

        t->rtre=create();//要先创建,不可以直接赋值
        t->rtre->w=x;

        return;

    }
    build(x,t->rtre);

}
if(x<t->w){

    if(t->ltre==NULL){
        t->ltre=create();
        t->ltre->w=x;

        return;

    }
    build(x,t->ltre);
}

}




int main(){

while(scanf("%d",&n)!=EOF){
    loc=0;
    Node *t=create();
    scanf("%d",&a[0]);
    t->w=a[0];
    for(int i=1;i<n;i++){
        scanf("%d",&a[i]);
        build(a[i],t);//t本身就是指针,所以取地址符号&不需要
    }
    pre(t);
    printf("\n");
    mid(t);
    printf("\n");
    aft(t);
    printf("\n");

}
return 0;
}

思路:重点是如何还原一棵二叉排序树。第一个整数为根,之后的数若小于该整数则置为左子树的根,若大于则置为右子树的根;往后的每一个整数,先和根比较,再决定去左边子树还是去右边子树,再与子树根做比较,直到成为叶子结点。


函数名功能传入传出
build()根据整数序列还原二叉排序树当前整数,树指针 
aft()后序遍历树指针 
mid()中序遍历树指针 
pre()
前序遍历
树指针 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值