C语言(用到c++引用&)二叉树的前序遍历(深度优先遍历)、中序遍历、后序遍历

前序遍历如上

中序就是213

后序是231

#include<stdio.h>
#include<stdlib.h>
typedef struct tree{
    char c;
    struct tree *left,*right;
}tree,*ptree;//定义一个树结点结构体
typedef struct list{
    ptree data;
    struct list *next;
}list,*plist;//辅助队列
typedef struct listht{
    list *front,*rear;
};//队列头尾指针
void preorder(ptree p){
    if(p!=NULL){
        printf("%c",p->c);
        preorder(p->left);
        preorder(p->right);
    }
}//前序遍历,调用自己递归
void inorder(ptree p){
    if(p!=NUll){
        preorder(p->left);
        printf("%c",p->c);
        preorder(p->right);
}
}//中序
void postorder(ptree p){
    if(p!=NUll){
        preorder(p->left);        
        preorder(p->right);
        printf("%c",p->c);
}
}//后序
int main(){
    ptree pnew;
    char c;
    ptree tree=NULL;
    plist phead=NULL,ptail=NULL,listnew=NULL,pcur=NULL;
    while(scanf("%c",&c)){
        if(c=='\n'){
            break;
        }
        pnew=(ptree) calloc(1,sizeof (tree));
        pnew->c=c;
        listnew=(plist) calloc(1,sizeof (list));
        listnew->data=pnew;
        if(NULL==tree){
            tree=pnew;
            phead=listnew;
            ptail=listnew;
            pcur=listnew;
        }else{
            ptail->next=listnew;
            ptail=listnew;
            if(NULL==pcur->data->left){
                pcur->data->left=pnew;
            }else if(NULL==pcur->data->right){
                pcur->data->right=pnew;
                pcur=pcur->next;
            }
        }
    }//创二叉树的过程
    preorder(tree);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值