/* 时间:2014.2.6 目的:题目1184:二叉树遍历ac.jobdu.com/problem.php?pid=1184 */ #include <stdio.h> #include <string.h> #include <malloc.h> char str[101]; typedef struct TreeNode{ struct TreeNode *left; struct TreeNode *right; char c; }TreeNode,*Tree; void Middle(Tree T)//中序遍历 { if(T!=NULL) { Middle(T->left); printf("%c ",T->c); Middle(T->right); } } int create(TreeNode ** T,int *index,int *n)//主要是第一个参数我纠结了一阵, //为什么必须用两个*呢?因为一个*只是表示所指的结构体为同一个位置,但是本身存放的指针的地址不是同一个, //比如,*a = *b = 4;但是a,b本身的地址是不同的,而本函数要求所指结构体的指针的的地址是相同的, //下面有让结构体指针的赋值为空的语句,这个可以用引用来代替,理解就不会这么吃力,可以用调试的方法的试一下 //我用的是a##单步测试的。。。 { if((*index) == (*n)) return 0; if(str[(*index)] == ‘#‘) { *T = NULL;//为空子树 (*index)++; //工作指针指向字符串的指针 } else { *T = (TreeNode*)malloc(sizeof(TreeNode)); (*T)->c = str[(*index)]; (*index)++; create(&((*T)->left),index,n);//创建左子树 create(&((*T)->right),index,n);//创建有字数 } return 0; } int main() { int inde, le; while(gets(str)) { Tree T = (Tree)malloc(sizeof(TreeNode)); le = strlen(str); inde = 0; create(&T,&inde,&le); Middle(T); printf("\n"); free(T); } return 0; } /* --------------- a## 思路:1.主要是递归生成左子树和右子树 a abc##de#g##f### c b e g d f a --------------- */
#include <stdio.h> #include <string.h> #include <malloc.h> char str[101]; typedef struct TreeNode{ struct TreeNode *left; struct TreeNode *right; char c; }TreeNode,*Tree; void Middle(Tree T) { if(T!=NULL) { Middle(T->left); printf("%c ",T->c); Middle(T->right); } } TreeNode* create(TreeNode * T,int *index,int *n)//这种方法不用两个*,因为函数本身提供返回值和上一个不同 { if((*index) == (*n)) return T; if(str[(*index)] == ‘#‘) { T = NULL; (*index)++; } else { T = (TreeNode*)malloc(sizeof(TreeNode)); T->c = str[(*index)]; (*index)++; T->left = create(T->left,index,n); T->right = create(T->right,index,n); } return T; } int main() { int inde, le; while(gets(str)) { Tree T = (Tree)malloc(sizeof(TreeNode)); le = strlen(str); inde = 0; T = create(T,&inde,&le); Middle(T); printf("\n"); free(T); } return 0; }
#include <stdio.h> #include <string.h> #include <malloc.h> char str[101]; typedef struct TreeNode{ struct TreeNode *left; struct TreeNode *right; char c; }TreeNode,*Tree; void Middle(Tree T) { if(T!=NULL) { Middle(T->left); printf("%c ",T->c); Middle(T->right); } } int create(Tree & T,int *index,int *n)//这个是引用(c++中的引用,c语言没有 ) { if((*index) == (*n)) return 0; if(str[(*index)] == ‘#‘) { T = NULL; (*index)++; } else { T = (TreeNode*)malloc(sizeof(TreeNode)); T->c = str[(*index)]; (*index)++; create(T->left,index,n); create(T->right,index,n); } return 0; } int main() { int inde, le; while(gets(str)) { Tree T = (Tree)malloc(sizeof(TreeNode)); le = strlen(str); inde = 0; create(T,&inde,&le); Middle(T); printf("\n"); free(T); } return 0; }
原文:http://blog.csdn.net/z_x_b5/article/details/18952907