问题描述
- 树的括号表示法怎么写
- #include
#include
#include
using namespace std;
struct treenode
{
char data;
treenode firstchild;
treenode *nextsibling;
};
treenode * creat_tree(char&a)
{ if((*a)=='')
{
a++;
}
if((*a)=='')
return NULL;
if((*a)==')')
{
a++;
return NULL;
}
if((*a)=='(')
{
a++;
}
treenode t=new treenode();
t->data=(a++);
t->firstchild=creat_tree(a);
t->nextsibling=creat_tree(a);
return t;
}
void show_tree(treenode *t)
{ //cout<<""123"";
if(t==NULL)
return;
cout<data;
for(treenode *p=t->firstchild;p!=NULL;p=p->nextsibling)
{
show_tree(p);
}
}
int main()
{ //char ch[100];
char *a;//[100];
gets(a);
// puts(a);
treenode *t=creat_tree(a);
show_tree(t);
}我写了一个,但又明显错误,希望大神能帮我改进。。
解决方案
#include<stdio.h>#include<stdlib.h>#include<memory.h>typedef struct BiTNode { char data; struct BiTNode *lchild; struct BiTNode *rchild; } *BiTree;BiTree CreateBiTree(BiTree T){ char ch; scanf(""%c""&ch); if (ch=='#'){ return NULL; }else { T = (BiTree)malloc(sizeof(struct BiTNode)) ; T->data = ch; T->lchild=CreateBiTree(T->lchild); T->rchild=CreateBiTree(T->rchild); return T; }}void PreOrder(BiTree &T){ if(T){ printf(""%c ""T->data); PreOrder(T->lchild); PreOrder(T->rchild); }}void InOrder(BiTree &T){ if(T){ InOrder(T->lchild); printf(""%c ""T->data); InOrder(T->rchild); }}void PostOrder(BiTree &T){ if(T){ PostOrder(T->lchild); PostOrder(T->rchild); printf(""%c ""T->data); }}void ShowBiTree(BiTree &bt){ if (bt!=NULL){ printf(""%c""bt->data); if (bt->rchild!=NULL||bt->lchild!=NULL){ printf(""(""); ShowBiTree(bt->lchild); if (bt->rchild!=NULL){ printf(""); } ShowBiTree(bt->rchild); printf("")""); } }}int main(){ printf(""请依次输入字符:
""); BiTree T; T = CreateBiTree(T); printf(""先序遍历:
""); PreOrder(T); printf(""
中序遍历:
""); InOrder(T); printf(""
后序遍历:
""); PostOrder(T); printf(""
用括号表示法输出二叉树:
""); ShowBiTree(T); printf(""
""); system(""pause""); return 0;}
时间: 2024-10-30 15:40:04