给定一系列整数,建立二叉排序树,输出前序、中序和后序遍历结果
#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() |
前序遍历
|
树指针 |