可学习的博客:
http://blog.chinaunix.net/uid-28639221-id-4678881.html
http://blog.csdn.net/cqnuztq/article/details/8896953
http://blog.csdn.net/u010187139/article/details/46778661
http://study.hhit.edu.cn/subject/CourseWare_Detail.aspx?TeachCourseWareID=231
实现代码:
1 #include <stdio.h> 2 #include <malloc.h> 3 #include <iostream> 4 5 //定义节点 6 typedef struct BiNode{ 7 char data; 8 struct BiNode *lch; 9 struct BiNode *rch; 10 }BiNode,*BiTree; 11 12 //先序拓展序列建立二叉树 13 void Create(BiTree &T) 14 { 15 T =(BiNode*) malloc (sizeof(BiNode)); 16 17 scanf(" %c",&T->data); 18 if(T->data=='#') T = NULL; 19 if(T){ 20 printf(""); 21 Create(T->lch); 22 Create(T->rch); 23 } 24 } 25 26 int TreeDeep(BiTree T)//树的深度 27 { 28 int deep = 0; 29 if(T){ 30 int leftdeep = TreeDeep(T->lch); 31 int rightdeep = TreeDeep(T->rch); 32 deep = leftdeep>=rightdeep?leftdeep+1:rightdeep+1; 33 } 34 } 35 36 //先序遍历 (递归) 37 void Preorder (BiTree T) 38 { 39 if (T) { 40 printf(" %c",T->data); // 访问根结点 41 42 Preorder(T->lch); // 遍历左子树 43 Preorder(T->rch);// 遍历右子树 44 } 45 } 46 47 //中序遍历 (递归) 48 void Inorder (BiTree T) 49 { 50 if(T) { 51 Inorder(T->lch); 52 53 printf(" %c",T->data); 54 55 Inorder(T->rch); 56 } 57 } 58 59 //后序遍历 (递归) 60 void Postorder (BiTree T) 61 { 62 if(T) { 63 Postorder(T->lch); 64 Postorder(T->rch); 65 66 printf(" %c",T->data); 67 } 68 } 69 70 //求二叉树叶子结点个数 71 72 int Leafcount(BiTree T,int &num) 73 { 74 if(T){ 75 if(T->lch ==NULL &&T->rch==NULL) 76 num++; 77 Leafcount(T->lch,num); 78 Leafcount(T->rch,num); 79 } 80 return num; 81 } 82 83 int main() 84 { 85 //建树 86 printf("The fuction Create() is called. "); 87 BiTree T; 88 Create(T); 89 90 //三种遍历递归算法 91 printf(" "); 92 printf("The fuction Preorder() is called. "); 93 Preorder(T); 94 95 printf(" "); 96 printf("The fuction Inorder() is called. "); 97 Inorder(T); 98 99 printf(" "); 100 printf("The fuction Postorder() is called. "); 101 Postorder(T); 102 printf(" "); 103 104 int deepth=TreeDeep(T); 105 printf("The fuction TreeDeep() is called. "); 106 printf("%d",deepth); 107 printf(" "); 108 109 int num=0; 110 Leafcount(T,num); 111 printf("The fuction Leafcount() is called. "); 112 printf("%d",num); 113 printf(" "); 114 115 }