数据结构试验——二叉树
数据结构试验——二叉树程序代码:
#include<iostream> using namespace std; #define Maxlen 100 typedef char Elemtype; typedef struct{ Elemtype data[Maxlen]; int length; }Tree; //链式定义 typedef struct node { Elemtype data; struct node *lchild; struct node *rchild; }Btree; void InitTree(Tree *t,int m) { t->length=m; for(int i=0;i<t->length;i++) t->data[i]='#'; cout<<"二叉树初始化成功!\n"; } void add(Tree *t,Elemtype a,int i) { t->data[i]=a; } void display(Tree *t) { cout<<"二叉树中的元素为:"; for(int j=0;j<t->length;j++) cout<<t->data[j]<<' '; cout<<endl; } //转化函数 void change(Tree *t) { Btree *stack[Maxlen]; int top=0,to=1; stack[top]=(Btree*)malloc(sizeof(Btree)); stack[top]->data=t->data[to-1]; top++; while(top>0) { top--; if((t->data[2*to-1]!='#') && (t->data[2*to]!='#')) { stack[top]->lchild=(Btree*)malloc(sizeof(Btree)); stack[top]->lchild->data=t->data[2*to-1]; stack[top]->rchild=(Btree*)malloc(sizeof(Btree)); stack[top]->rchild->data=t->data[2*to]; top++; to++; } } cout<<"转化成功!\n"; } void main() { int n; Elemtype a; Tree tr; char b; cout<<"请输入需要输入的树的结点的个数:"; cin>>n; InitTree(&tr,n); display(&tr); for(int i=0;i<n;i++) { cout<<"请输入二叉树的第"<<i+1<<"个结点,若为空结点,请输入#:"; cin>>a; add(&tr,a,i); } cout<<"是否需要显示二叉树的元素y/n:"; cin>>b; if (b=='y'|| b=='Y') display(&tr); change(&tr); }