|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Martine 于 2018-6-25 18:08 编辑
题:将如图所示的深林转化为二叉树(易)
将父子关系表示为 父(子,子......)
则该森林的数据结构可以表示为 A(B(EF)C(G)D)
- #include <stdio.h>
- #include <stdlib.h>
- typedef char ElemType;
- typedef struct node
- {
- ElemType data;
- struct node *lchild, *rchild;
- }node, *btree;
- void CreateBtree(btree *root)
- {
- ElemType c;
- scanf("%c", &c);
- if('#' == c){
- *root = NULL;
- }else{
- *root = (btree)malloc(sizeof(node));
- (*root)->data = c;
- CreateBtree(&(*root)->lchild);
- CreateBtree(&(*root)->rchild);
- }
- }
- void in(btree root)
- {
- if(root)
- {
- in(root->lchild);
- printf("[%c ] ", root->data);
- in(root->rchild);
- }
- }
- void herit(btree root)
- {
- printf("%c", root->data);
- if(root->lchild || root->rchild){
- printf("(");
- if(root->lchild)
- herit(root->lchild);
- if(root->rchild)
- herit(root->rchild);
- printf(")");
- }
- }
- int main(void)
- {
- btree root;
- CreateBtree(&root);
- in(root);
- putchar('\n');
- herit(root);
- putchar('\n');
- printf(" \n######Wors*/k done!#######\n");
- return 0;
- }
复制代码
如何增加边界检测才能去掉多余的括号 ?求解!!
貌似是对了?
我也不确定,这个结果是调试出来的,再换几组数据测试一下
- #include <stdio.h>
- #include <stdlib.h>
- typedef char ElemType;
- typedef struct node
- {
- ElemType data;
- struct node *lchild, *rchild;
- }node, *btree;
- char data[] = "ABE#F##CG##D###";
- char *p = data;
- void CreateBtree(btree *root)
- {
- ElemType c;
- //scanf("%c", &c);
- c = *p++; // 为 debug 方便
- if('#' == c){
- *root = NULL;
- }
- else{
- *root = (btree)malloc(sizeof(node));
- (*root)->data = c;
- CreateBtree(&(*root)->lchild);
- CreateBtree(&(*root)->rchild);
- }
- }
- void in(btree root)
- {
- if(root)
- {
- in(root->lchild);
- printf("[%c ] ", root->data);
- in(root->rchild);
- }
- }
- void herit(btree root)
- {
- printf("%c", root->data);
- if(root->lchild || root->rchild){
- if(root->lchild)
- printf("(");
- if(root->lchild)
- herit(root->lchild);
- if(root->rchild)
- herit(root->rchild);
-
- //if(root->rchild)
- // printf(")");
- }
- else
- printf(")");
- }
- int main(void)
- {
- btree root;
- CreateBtree(&root);
- in(root);
- putchar('\n');
- herit(root);
- putchar('\n');
- printf(" \n######Wors*/k done!#######\n");
- return 0;
- }
复制代码
|
|