本文共 1708 字,大约阅读时间需要 5 分钟。
#include "stdlib.h" #include "stdio.h" #include "Windows.h"#includeusing namespace std; /*引入头文件*/struct tnode /*定义二叉树存储结构*/{ char data; struct tnode*lchild; struct tnode*rchild;};struct tnode tree; /*定义二叉树指针*/void createtree(struct tnode*t) /*创建函数*/{ struct tnode*p=t; /*把二叉树指针给p*/ char check; if(p->lchild==NULL||p->rchild==NULL) /*判断左右子树是否为空*/ { printf("please enter the data:"); /*输入根结点数据*/ scanf("%c",&(p->data)); getchar(); } if(p->lchild==NULL) { printf("%c leftchild is null.Add? y/n\n",p->data); /*左子树空,询问是否创建*/ scanf("%c",&check); getchar(); if(check=='y') { struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*开辟空间*/ q->lchild=NULL; q->rchild=NULL; p->lchild=q; createtree(q); } } if(p->rchild==NULL) { printf("%c rightchild is NULL.Add? y/n\n",p->data); /*右子树空,询问是否创建*/ scanf("%c",&check); getchar(); if(check=='y') { struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*开辟空间*/ q->lchild=NULL; q->rchild=NULL; p->rchild=q; /*连到二叉树上*/ createtree(q); } }}void preorder(struct tnode*t) /*先序遍历函数*/{ if(t) { printf("%c ",t->data); /*输出根结点数据*/ preorder(t->lchild); preorder(t->rchild); }}void inorder(struct tnode*t) /*中序遍历函数*/{ if(t) { inorder(t->lchild); printf("%c ",t->data); inorder(t->rchild); }}void postorder(struct tnode*t) /*后序遍历函数*/{ if(t) { postorder(t->lchild); postorder(t->rchild); printf("%c ",t->data); }}void main(){ //clrscr(); /*清屏函数*/ tree.lchild=NULL; /*左子树*/ tree.rchild=NULL; /*右子树*/ createtree(&tree); /*创建二叉树*/ preorder(&tree); /*先序遍历*/ printf("\n"); inorder(&tree); /*中序遍历*/ printf("\n"); postorder(&tree); /*后序遍历*/}
转载地址:http://wbsgi.baihongyu.com/