分类: C/C++
2011-05-31 10:34:05
/*
* 二叉树简单实现、递归方式
* Lzy 2011-5-24
*/
#include
#define ElemType int
typedef struct node
{
ElemType data; /*数据域*/
struct node *left; /*左子树指针*/
struct node *right; /*右子树指针*/
}BTree;
void BTreeCreate(BTree **tp) /*二叉树的构建*/
{
int x;
printf("输入(小于0不输入):");
scanf("%d",&x);
if(x < 0) /*递归条件结束*/
{
tp = NULL;
return ;
}
(*tp) = (BTree *)malloc(sizeof(BTree)); /*分配内存空间*/
(*tp)->data = x; /*数据域赋值*/
BTreeCreate(&((*tp)->left)); /*递归调用*/
BTreeCreate(&((*tp)->right));
return ;
}
void PreOrder(BTree *tp) /*前序遍历、递归方式*/
{
if(tp == NULL)
return ;
else
{
printf("%d ",tp->data); /*访问根节点*/
PreOrder(tp->left); /*遍历左子树*/
PreOrder(tp->right); /*遍历右子树*/
}
}
int main(void)
{
BTree *root;
BTreeCreate(&root);
PreOrder(root);
}