标签:中序遍历 data pre 线性结构 printf n+1 font 二叉查找树 ges
二叉树
1 #include<cstdio> 2 typedef struct node{ 3 char data; 4 struct node *leftson; 5 struct node *rightson; 6 }BiNode,*BiTree; 7 8 void creatBiTree (BiTree & T){//前序建树 9 char c; 10 scanf("%c",&c); 11 if(c==‘#‘)T=NULL; 12 else { 13 T = new BiNode; 14 T->data=c; 15 creatBiTree(T->leftson); 16 creatBiTree(T->rightson); 17 } 18 } 19 20 void preorder (BiTree T){//先序遍历 21 if(T){ 22 printf("%c ",T->data); 23 preorder(T->leftson); 24 preorder(T->rightson); 25 } 26 } 27 28 void inorder (BiTree T){//中序遍历 29 if(T){ 30 inorder(T->leftson); 31 printf("%c ",T->data); 32 inorder(T->rightson); 33 } 34 } 35 36 void postorder (BiTree T){//后序遍历 37 if(T){ 38 postorder(T->leftson); 39 postorder(T->rightson); 40 printf("%c ",T->data); 41 } 42 } 43 44 int depth (BiTree T){//求二叉树深度 45 int dep=0; 46 int depl=0,depr=0; 47 if(!T)dep=0; 48 else { 49 depl=depth(T->leftson); 50 depr=depth(T->rightson); 51 dep=1+(depl>depr?depl:depr); 52 } 53 return dep; 54 } 55 56 int sumleaf (BiTree T){//求叶子节点个数 57 int sum=0; 58 int l,r; 59 if(T){ 60 if((!T->leftson)&&(!T->rightson))sum++; 61 l=sumleaf(T->leftson); 62 sum+=l; 63 r=sumleaf(T->rightson); 64 sum+=r; 65 } 66 return sum; 67 } 68 69 int main(){ 70 BiTree T; 71 creatBiTree(T); 72 preorder (T);printf("\n"); 73 inorder (T);printf("\n"); 74 postorder (T);printf("\n"); 75 printf("%d\n",depth(T)); 76 printf("%d\n",sumleaf(T)); 77 return 0; 78 }
eg:
(先序) ABC##DE#G##F### (#表示空)
标签:中序遍历 data pre 线性结构 printf n+1 font 二叉查找树 ges
原文地址:http://www.cnblogs.com/wjting/p/6032668.html