/*
* 非完全二叉树
* 2018.10.23
* @L.F
*
*/
#include <stdio.h>
#include <stdlib.h>
//定义结点结构体
typedef struct node{
char id; //编号
struct node *lchild; //保存左子树地址的指针
struct node *rchild; //保存右子树地址的指针
}bitree_t;
//创建一个非完全二叉树
bitree_t *bitree_create()
{
char c;
scanf("%c", &c);
if(c == '#')
{
return NULL;
}
bitree_t *root = (bitree_t *)malloc(sizeof(bitree_t));
root->id = c;
root->lchild = bitree_create();
root->rchild = bitree_create();
return root;
}
//先序遍历:根 左 右
void bitree_order_before(bitree_t *root)
{
//先打印根结点
printf("%c ", root->id);
//判断是否存在左右子树,如果存在,则将其当作根继续往下遍历
if(root->lchild != NULL)
{
bitree_order_before(root->lchild);
}
if(root->rchild != NULL)
{
bitree_order_before(root->rchild);
}
return ;
}
//中序遍历:左 根 右
void bitree_order_in(bitree_t *root)
{
if(root->lchild != NULL)
{
bitree_order_in(root->lchild);
}
printf("%c ", root->id);
if(root->rchild != NULL)
{
bitree_order_in(root->rchild);
}
return ;
}
//后序遍历:左 右 根
void bitree_order_after(bitree_t *root)
{
if(root->lchild != NULL)
{
bitree_order_after(root->lchild);
}
if(root->rchild != NULL)
{
bitree_order_after(root->rchild);
}
printf("%c ", root->id);
return ;
}
int main(int argc, const char *argv[])
{
bitree_t *root = bitree_create();
bitree_order_before(root);
putchar(10);
bitree_order_in(root);
putchar(10);
bitree_order_after(root);
putchar(10);
return 0;
}