1.二叉树的基本结构
二叉树不再是普通的线性结构,它的结构类似树枝,一个结点接分支。我们可以把二叉树细分成多个根带它的左、右子树。
二叉树
typedef int TDataType;
typedef struct Tree
{
TDataType data;
struct Tree* left;
struct Tree* right;
}T;
2.二叉树的接口函数
前序
void PrevOrder(T* root);
void PrevOrder(T* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
printf("%d ", root->data);
PrevOrder(root->left);
PrevOrder(root->right);
}
中序
void InOrder(T* root);
void InOrder(T* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
InOrder(root->left);
printf("%d ", root->data);
InOrder(root->right);
}
后序
void PostOrder(T* root);
void PostOrder(T* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->data);
}
节点个数
int TreeSize(T* root);
int TreeSize(T* root)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
叶子节点的个数
int TreeLeafSize(T* root);
int TreeLeafSize(T* root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
else
{
return 0 + TreeSize(root->left) + TreeSize(root->right);
}
}
销毁
void TreeDestory(T* root);
void TreeDestory(T* root)
{
if (root->left == NULL&&root->right==NULL)
{
free(root);
root = NULL;
}
TreeDestory(root->left);
TreeDestory(root->right);
}
3.二叉树的使用
int main()
{
T* A=(T*)malloc(sizeof(T));
A->data = 1, A->left = NULL, A->right = NULL;
T* B = (T*)malloc(sizeof(T));
B->data = 2, B->left = NULL, B->right = NULL;
T* C = (T*)malloc(sizeof(T));
C->data = 3, C->left = NULL, C->right = NULL;
T* D = (T*)malloc(sizeof(T));
D->data = 4, D->left = NULL, D->right = NULL;
T* E = (T*)malloc(sizeof(T));
E->data = 5, E->left = NULL, E->right = NULL;
A->left = B;
B->left = C;
B->right = D;
A->right = E;
PrevOrder(A);
printf("\n");
InOrder(A);
printf("\n");
PostOrder(A);
printf("\n");
printf("%d\n",TreeSize(A));
printf("%d\n", TreeLeafSize(A));
TreeDestory(A);
return 0;
}