二叉树包括顺序存储和链式存储,这里只说链式存储,二叉树的每个结点和双链表有些类似,但是数的结构要比双链表复杂,在构造树的过程中涉及到递归调用的问题,递归的问题往往是很复杂的问题,因此,这里单独说二叉树的构建。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
//定义二叉树
typedef struct node{
int data;//数据元素
struct node *left;//指向左子树
struct node *right;//指向右子树
}BTree;
//构造二叉树
int BTreeCreate(BTree **tp)
{
//构造方法,或者说构造顺序:从左子树开始构造
int x;
scanf("%d",&x);
if(x<0)
{
*tp=NULL;//指针为空,树节点中的某个指针为空
return 0;
}
*tp=(BTree*)malloc(sizeof(BTree));//将树节点中指针指向该地址空间
if(tp==NULL)
return 0;
(*tp)->data=x;
BTreeCreate(&((*tp)->left));
BTreeCreate(&((*tp)->right));
return 1;
}
int main()
{
BTree *tree;
printf("Create binary tree:\n");
BTreeCreate(&tree);
return 0;
}