二叉树的结构定义:
typedef struct binNode* binTree;
struct binNode
{
int element;
binTree leftChild, rightChild;
};
二叉树的建立:
binTree creatBintree()
{
int a;
binTree b;
scanf("%d", &a);
if (0 == a) //如果输入0,则停止创建
b = NULL;
else
{
b = (binTree)malloc(sizeof(struct binNode));
b->element = a;
b->leftChild = creatBintree();
b->rightChild = creatBintree();
}
return b;
}
二叉树的建立的完整代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct binNode* binTree;
struct binNode
{
int element;
binTree leftChild, rightChild;
};
binTree creatBintree()
{
int a;
binTree b;
scanf("%d", &a);
if (0 == a) //如果输入0,则停止创建
b = NULL;
else
{
b = (binTree)malloc(sizeof(struct binNode));
b->element = a;
b->leftChild = creatBintree();
b->rightChild = creatBintree();
}
return b;
}
void print(binTree b) //先序遍历
{
if (b!=NULL)
{
printf("%d\n", b->element);
print(b->leftChild);
print(b->rightChild);
}
}
int main(void)
{
binTree bin = creatBintree();
print(bin);
return 0;
}
注:这篇文章主要实现二叉树的建立,二叉树的遍历方式将在后续文章中叙述。