1. 程式人生 > >擴展二叉樹

擴展二叉樹

style oid bsp length amp nod int blog truct

擴展二叉樹

一、心得

二、題目及分析

給定擴展二叉樹的先序序列,求二叉樹的中序和後序序列

輸入
ABD..EF..G..C..
輸出
dbfegac
dfgebca

三、代碼及結果

 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 }

技術分享

擴展二叉樹