构思:
1.建立跟节点,装载输入的字符
2.根据输入的字符'#'判断是否存在做孩子
是,重复1
否,返回
3.判断是否存在右孩子
是,重复1,
否,返回
这里用到了递归思想。
遍历树可以跟建树的顺序一样,但也可以用不同的方法遍历,例如中序。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxsize 30
typedef struct node //节点结构体
{
char c;
struct node *lchild, *rchild;
}nod, *nodlk;
void build_tree(nodlk *root){ //使用二级指针是为了不用返回传进的指针,使用一级指针则要返回指针给主函数,否则在主函数无法使用此树
*root = (nodlk)malloc(sizeof(nod));
char c;
scanf("%c",&c);
if (c == '#'){ //用#表示孩子为空
(*root)->lchild = NULL;
(*root)->rchild = NULL;
return ;
}
else
{
(*root)->c = c;
build_tree(&((*root)->lchild));
build_tree(&((*root)->rchild));
}
return;
}
void show(nodlk root){ //打印该树
if(root != NULL){
printf("%c",root->c);
show(root->lchild);
show(root->rchild);
}
return ;
}
int main(void)
{
nodlk root;
printf("you can build a tree like: ");
build_tree(&root);
printf("-------------------------/n");
printf("your tree had build success: ");
show(root);
printf("/n");
return 0;
}