扩展二叉树
一、心得
二、题目及分析
给定扩展二叉树的先序序列,求二叉树的中序和后序序列
输入ABD..EF..G..C..输出dbfegacdfgebca
三、代码及结果
1 //扩展二叉树 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 string s="ABD..EF..G..C.."; 7 int m=-1; 8 9 typedef struct node{ 10 char data; 11 node *lchild,*rchild; 12 }*tree; 13 14 15 void creatTree(tree &bt){ 16 if(s[++m]!=‘.‘&&m<s.length()){ 17 bt=new node; 18 bt->data=s[m]; 19 cout<<bt->data<<" "<<m<<" "; 20 creatTree(bt->lchild); 21 creatTree(bt->rchild); 22 } 23 else bt=NULL; 24 25 } 26 //先序遍历 27 void printxx(tree bt){ 28 if(bt){ 29 cout<<bt->data<<" "; 30 printxx(bt->lchild); 31 printxx(bt->rchild); 32 } 33 } 34 35 //中序遍历 36 void printzx(tree bt){ 37 if(bt){ 38 printzx(bt->lchild); 39 cout<<bt->data<<" "; 40 printzx(bt->rchild); 41 } 42 } 43 44 //后序遍历 45 void printhx(tree bt){ 46 if(bt){ 47 printhx(bt->lchild); 48 printhx(bt->rchild); 49 cout<<bt->data<<" "; 50 } 51 } 52 53 int main(){ 54 tree treeHead; 55 creatTree(treeHead); 56 cout<<endl; 57 printxx(treeHead); 58 cout<<endl; 59 printzx(treeHead); 60 cout<<endl; 61 printhx(treeHead); 62 return 0; 63 }
时间: 2024-10-24 02:29:07