【文件属性】:
文件名称:打印树结构
文件大小:1KB
文件格式:CPP
更新时间:2015-01-13 11:59:28
数据结构
#include
#include
#include
#include
#define NULL 0
#define MAXSIZE 81
typedef struct Node
{
struct Node *lchild;
struct Node *parent;
char data;
int deep;
struct Node *rchild;
}treeNode;
void createtree(treeNode *tree,char str[])
{
treeNode *p,*q,*t;
int i=0;
q=tree;
for(i=1;ilchild==NULL)
{
p=(treeNode *)malloc(sizeof(treeNode));
p->data=str[i];
p->lchild=p->rchild=NULL;
p->deep=(q->deep)+1;
q->lchild=p;
p->parent=q;
q=p;
}
else
{
t=q;
q=q->lchild;
while(q->rchild!=NULL)
{
q=q->rchild;
}
p=(treeNode *)malloc(sizeof(treeNode));
p->data=str[i];
p->deep=q->deep;
p->lchild=p->rchild=NULL;
q->rchild=p;
p->parent=t;
q=p;
}
}
else
{
q=q->parent;
}
}
else
{
break;
}
}
}
void putout(treeNode *tree)
{
int i;
if(tree)
{
for(i=tree->deep;i>0;i--)
printf(" ");
printf("%c\n",tree->data);
putout(tree->lchild);
putout(tree->rchild);
}
}
void main()
{
treeNode *tree;
char str[MAXSIZE];
printf("请输入树(空格表示返回双亲节点):\n");
scanf("%s",str);
tree=(treeNode *)malloc(sizeof(treeNode));
tree->data=str[0];
tree->deep=0;
tree->lchild=tree->rchild=NULL;
createtree(tree,str);
printf("输入的树是:\n");
putout(tree);
printf("完毕!");
}