使用先序创建一颗二叉树,并通过先序,中序,后序来遍历二叉树,得到遍历顺序。
例如://ABD##EF###C#GH#I# 来先序创建二叉树
代码如下
#include <stdio.h>
#include <malloc.h>
#include<stdlib.h>
typedef struct biNode
{
char data; //结点数据类型
struct biNode *lchild, *rchild;
}bitree; //定义左、右孩子为指针型
int max = 0;
bitree * createtree(bitree * BT)
{
char ch;
scanf("%c", &ch);
if (ch == '#') BT = NULL;
else
{
BT = (bitree *)malloc(sizeof(bitree));
BT->data = ch;
BT->lchild = createtree(BT->lchild);
BT->rchild = createtree(BT->rchild);
}
return BT;
}
void preorder(bitree * root) //先序遍历二叉树
{
bitree *p;
p = root;
if (p != NULL)
{
printf("%c", p->data); /*访问根结点*/
preorder(p->lchild); /*递归遍历左子树*/
preorder(p->rchild); /*递归遍历右子树*/
}
}
void inorder(bitree * root) //中序遍历二叉树
{
bitree *p;
p = root;
if (p != NULL)
{
inorder(p->lchild); /*递归遍历左子树*/
printf("%c", p->data); /*访问根结点*/
inorder(p->rchild); /*递归遍历右子树*/
}
}
void postorder(bitree * root) //后序遍历二叉树
{
bitree *p;
p = root;
if (p != NULL)
{
postorder(p->lchild); /*递归遍历左子树*/
postorder(p->rchild); /*递归遍历右子树*/
printf("%c", p->data); /*访问根结点*/
}
}
int shendu(bitree *root)
{
bitree *p;
p = root;
if (!p)
{
return 0;
}
int d1 = shendu(p->lchild);
int d2 = shendu(p->rchild);
return (d1 > d2 ? d1 : d2) + 1;
}
int display(bitree *root)
{
bitree *p;
p = root;
if (p==NULL)
{
display(p->lchild);
return 0;
}
}
int main()
{
bitree *bt;
bt = (bitree*)malloc(sizeof(bitree));
printf("先序递归创建二叉树:\n");
bt = createtree(bt);
printf("先序遍历二叉树:\n");
preorder(bt);
printf("\n");
printf("中序遍历二叉树:\n");
inorder(bt);
printf("\n");
printf("后序遍历二叉树:\n");
postorder(bt);
printf("\n");
printf("二叉树的深度为:\n");
printf("%d\n", shendu(bt));
system("pause");
}
//ABD##EF###C#GH#I#