利用二叉树前序遍历方法创建一棵二叉树(前序建立二叉树是输入的序列是:AB#D##C#E## ),然后对该二叉树进行前序遍历(非递归),并输出遍历结果
#include#include typedef struct node { char data; struct node *lchild,*rchild; }binnode; typedef binnode *bintree; bintree creatbintree() { char ch; bintree t; if((ch=getchar())=='#') t=NULL; else { t=(binnode*)malloc(sizeof(binnode)); t->data=ch; t->lchild=creatbintree(); t->rchild=creatbintree(); } return t; } void preorder1(bintree t) //前序遍历// { if(t) { printf("%c",t->data); preorder1(t->lchild); preorder1(t->rchild); } } void inorder(bintree t) //中序遍历// { if(t) { inorder(t->lchild); printf("%c",t->data); inorder(t->rchild); } } void postorder(bintree t) //后序遍历// { if(t) { postorder(t->lchild); postorder(t->rchild); printf("%c",t->data); } } int numofnode(bintree t) //计算结点个数// { if(t==NULL) return 0; else return(numofnode(t->lchild)+numofnode(t->rchild)+1); } int main() { Bintree FPP; printf("请输入前序建立二叉树的输入序列:n"); FPP=creatbintree(); printf("前序遍历输出:n"); preorder1(FPP); printf("n中序遍历输出:n"); inorder(FPP); printf("n后序遍历输出:n"); postorder(FPP); printf("n该二叉树结点总数:n%dn",numofnode(FPP)); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)