C语言递归创建一颗二叉树

在这里给出结构体信息:

typedef struct tree {
struct tree   *lchild;    //左孩子节点
struct tree *rchild;    //右孩子节点
char data;//数据域

}Tree,*Bitree;

在图纸上画出自己所要创建的二叉树,这里是用先序遍历的方法来创建一颗二叉树:

空节点用#代替,这里给出一个二叉树的输入例子:

ABD##E##C##   

代表的是


下面是创建这棵树的代码:

Bitree CreateBitree(Bitree T)//先序创建一颗二叉树
{
char  e;
scanf_s("%c", &e);
fflush(stdin);
if (e != '#')     //判断当前输入的字符
{

T = (Bitree)malloc(sizeof(Tree)); //分配存贮空间
T->data = e;
T->lchild = NULL;
T->rchild = NULL;
T->lchild = CreateBitree(T->lchild); //递归创建左孩子节点值
T->rchild = CreateBitree(T->rchild);   //递归创建右孩子节点值
}
return T;
}

创建完之后,你就可以用任何一种遍历方式来遍历它了,实现二叉树的算法也就有了前提条件。

猜你喜欢

转载自blog.csdn.net/kuishao1314aa/article/details/79709956