1. 程式人生 > 實用技巧 >二叉樹鏈式儲存結構下的建立及遍歷演算法

二叉樹鏈式儲存結構下的建立及遍歷演算法

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <strings.h>
 4 #define MAX 100
 5 
 6 char * p;
 7 typedef struct BTree{
 8     char * str;
 9     struct BTree * lchild;
10     struct BTree * rchild;
11 }BTree;
12 
13 BTree* creat_tree(){
14     BTree* temp;
15     while(*p=='
')p++; 16 if(*p=='#'){ 17 p++; 18 return NULL; 19 } 20 if(*p!=' '){ 21 int i=0; 22 temp = (BTree *)malloc(sizeof(BTree)); 23 temp->str[i++]=*p++; 24 temp->lchild=creat_tree(); 25 temp->rchild=creat_tree(); 26 } 27 return
temp; 28 } 29 30 void pre_visit(BTree* node){ 31 printf("%c",node->str); 32 if(node->lchild!=NULL)pre_visit(node->lchild); 33 if(node->rchild!=NULL)pre_visit(node->rchild); 34 } 35 int main() 36 { 37 char tree[MAX];p=tree; 38 BTree * head; 39 printf("Please input the tree(use char and #)\n要求按照先序遍歷的方式輸入,加上#進行區分\n例如123# #4##5##:\n
"); 40 //scanf("%s",tree); 41 gets(tree); 42 43 if(*p!='\0'&&*p!=' '&&*p!='#'){ 44 head=(BTree *)malloc(sizeof(BTree)); 45 int i=0; 46 head->str[i++]=*p++; 47 //printf("head is %c",head->str); 48 head->lchild=creat_tree(); 49 head->rchild=creat_tree(); 50 } 51 52 printf("tree is :\n"); 53 pre_visit(head); 54 return 0; 55 }
BinTree