#include<stdio.h>
#include<string.h> #include<stdlib.h> typedef struct BiTNode { char data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; BiTree Create(BiTree T) { char ch; ch=getchar(); if(ch=='#') T=NULL; else { T=(BiTNode *)malloc(sizeof(BiTNode)); if(!T)printf("Error!"); T->data=ch; T->lchild=Create(T->lchild); T->rchild=Create(T->rchild); } return T; } void Preorder(BiTree T) { if(T) { printf("%c",T->data); Preorder(T->lchild); Preorder(T->rchild); } } void Inorder(BiTree T)
{ if(T) { Inorder(T->lchild); printf("%c",T->data); Inorder(T->rchild); } } void Postorder(BiTree T)
{ if(T) { Postorder(T->lchild); Postorder(T->rchild); printf("%c",T->data); } } int leaves(BiTree T) { int sum=0,m,n; if(T) { if((!T->lchild)&&(!T->rchild))sum++; m=leaf(T->lchild); sum+=m; n=leaf(T->rchild); sum+=n; } return sum; } void main() { int sum; BiTree T; printf("请以先序遍历的方式输入二叉树(结点没有左右孩子时用以#表示)\n"); T=Create(T); printf("先序遍历:"); Preorder(T); printf("\n"); printf("中序遍历:"); Inorder(T); printf("\n"); printf("后序遍历:"); Postorder(T); printf("\n"); printf("叶子结点个数为:\n"); sum=leaves(T); printf("%d",sum); } |
|