#include #include /*上面为动态分配内存空间函数*/ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define NULL 0 #define node_len sizeof(struct BiTNode) #define elemtype char /*elemtype可以更改为任意数据类型*/ /*注意,当elemtype改了,有些输出格式也要改*/ #define status int /*对结点访问的函数的类型*/ #define scanfformat "%c" #define printfformat "%c " struct BiTNode {elemtype data;struct BiTNode *lchild,*rchild;}; CreateBiTree(struct BiTNode **T) /*建树这里的参数是用来返回树的根值的,所以应该是指向(*T)的指针,因改为(**T),还有一种方法就是使用RETURN返回数的根.下面代码对应的T也都改为*T*/ {elemtype ch; scanf(scanfformat,&ch); if(ch==' ')(*T)=NULL; /*以空格的输入代表空树*/ else {if(!((*T)=(struct BiTNode *)malloc(node_len)))exit(OVERFLOW); (*T)->data=ch; CreateBiTree((*T)->lchild); CreateBiTree((*T)->rchild); } return OK; } PreOrderTraverse(struct BiTNode *T,status (*Visit)(elemtype e)) /*先序遍历二叉树递归算法,对每一个结点调用Visit函数*/ {if(T) {if((*Visit)(T->data)) /*(*Visit)相当于PrintElement*/ if(PreOrderTraverse(T->lchild,(*Visit))) if(PreOrderTraverse(T->rchild,(*Visit)))return OK; return ERROR; } else return OK; } status PrintElement(elemtype e) /*输出元素*/ {printf(printfformat,e); return OK; } main() {struct BiTNode *T; /*T是指向根结点的指针*/ printf("input a binary tree in the preorder:(space represents the null node)\n"); CreateBiTree(&T); //这里相应改为&Tprintf(printfformat,T->data); printf("preorder traverse(print each tree node without the null nodes):\n"); PreOrderTraverse(T,PrintElement); printf("\n"); getch(); }
|