#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
struct LBinaryTreeNode//二叉树结点
{
ElemType data;
struct LBinaryTreeNode * lchild;
struct LBinaryTreeNode * rchild;
struct LBinaryTreeNode * parent;
};
typedef struct LBinaryTreeNode *PLBTreeNode;//结点指针类型
typedef PLBTreeNode *PLBTree;//指向结点指针的指针/树根
PLBTreeNode parent_seq(PLBTreeNode p)//求父结点
{
if(p==NULL)
return NULL;
else
return p->parent;
}
PLBTreeNode leftchild_seq(PLBTreeNode p)//求左结点
{
if(p==NULL)
return NULL;
else
return p->lchild;
}
PLBTreeNode rightchild_seq(PLBTreeNode p)//求右结点
{
if(p==NULL)
return NULL;
else
return p->rchild;
}
PLBTreeNode createRest_BTree()//递归创建从根开始的二叉树
{
PLBTreeNode rootnode;
char ch;
scanf("%c ",&ch);
if(ch=='#')
{
rootnode=NULL;
return rootnode;
}
else
{
rootnode=(PLBTreeNode)malloc(sizeof(struct LBinaryTreeNode));
if(rootnode==NULL)
{
printf("创建失败!\n");
return 0;
}
else
{
rootnode->data=ch;
rootnode->lchild=createRest_BTree();//构造左子树
rootnode->rchild=createRest_BTree();//构造右子树
}
}
return rootnode;
}
PLBTree create_BTree(void)//创建完整二叉树
{
PLBTree roottree=(PLBTree)malloc(sizeof(PLBTreeNode));
if (roottree!=NULL)
*roottree=createRest_BTree( );//递归创建从根开始的二叉树
return roottree;
}
void visit(PLBTreeNode p)//访问结点数据
{
printf("%c ",p->data);
}
void preOrder(PLBTreeNode p)//先序访问
{
if (p==NULL)
return;
visit(p);
preOrder(leftchild_seq(p));
preOrder(rightchild_seq(p));
}
void inOrder(PLBTreeNode p)//中序访问
{
if (p==NULL)
return;
inOrder(leftchild_seq(p));
visit(p);
inOrder(rightchild_seq(p));
}
void postOrder(PLBTreeNode p)//后序访问
{
if (p==NULL)
return;
postOrder(leftchild_seq(p));
postOrder(rightchild_seq(p));
visit(p);
}
int main()
{
PLBTree tree=create_BTree();//结束输入#
preOrder(*tree);
putchar('\n');
inOrder(*tree);
putchar('\n');
postOrder(*tree);
return 0;
}