#include<stdio.h> #include<math.h> #include<stdlib.h> #include<malloc.h> typedef struct Node { int data; struct Node *LChild; struct Node *RChild; } BitNode,*BitTree; //前序建立二叉树,遇到-1停止 BitTree PreCreate(BitTree T) { int n; //printf("前序建立二叉树:请输入:\n"); scanf("%d",&n); if(n==-1)T=NULL; else{ T=(BitTree)malloc(sizeof(BitNode)); T->data=n; T->LChild=PreCreate(T->LChild); T->RChild=PreCreate(T->RChild); } return T; } //中序建立二叉树:不可行 BitTree MidCreate(BitTree T) { int n; //printf("中序建立二叉树:请输入:\n"); scanf("%d",&n); if(n==-1)T=NULL; else{ T=(BitTree)malloc(sizeof(BitNode)); T->LChild=MidCreate(T->LChild); T->data=n; T->RChild=MidCreate(T->RChild); } return T; } //后序建立二叉树:不唯一 BitTree LastCreate(BitTree T) { int n; //printf("后序建立二叉树:请输入:\n"); scanf("%d",&n); if(n==-1)T=NULL; else{ T=(BitTree)malloc(sizeof(BitNode)); T->LChild=LastCreate(T->LChild); T->RChild=LastCreate(T->RChild); T->data=n; } return T; } //先序遍历 void PreRead(BitTree T) { if(T) { printf("%d",T->data); PreRead(T->LChild); PreRead(T->RChild); } } //中序遍历 void MidRead(BitTree T) { if(T) { MidRead(T->LChild); printf("%d",T->data); MidRead(T->RChild); } } //后序遍历 void LastRead(BitTree T) { if(T) { LastRead(T->LChild); LastRead(T->RChild); printf("%d",T->data); } } int main() { printf("前序建立二叉树:请输入:\n"); BitNode *T=PreCreate(T); printf("前序遍历:"); PreRead(T); printf("\n"); printf("中序遍历:"); MidRead(T); printf("\n"); printf("后序遍历:"); LastRead(T); printf("\n"); /* printf("中序建立二叉树:请输入:\n"); BitNode *T1=MidCreate(T1); printf("前序遍历:"); PreRead(T1); printf("\n"); printf("中序遍历:"); MidRead(T1); printf("\n"); printf("后序遍历:"); LastRead(T1); printf("\n"); printf("后序建立二叉树:请输入:\n"); BitNode *T2=LastCreate(T2); printf("前序遍历:"); PreRead(T2); printf("\n"); printf("中序遍历:"); MidRead(T2); printf("\n"); printf("后序遍历:"); LastRead(T2); printf("\n"); */ return 0; }
时间: 2024-11-05 23:36:12