代码的树的结构为
1
2 3
4 5 6 7
8
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
/* 结构体 */
typedef struct treenode
{
struct treenode *pstLeftChild;
struct treenode *pstRightChild;
int idata;
}TreeNode_S,TreeHead_S;
/* 初始化树 */
TreeHead_S *InitTree(TreeNode_S *pstNode)
{
TreeHead_S *tree = pstNode;
return tree;
}
/* 创建树的节点 */
TreeNode_S *CreateTreeNode(int idata, TreeNode_S *pstleftchild, TreeNode_S *pstrightchild)
{
TreeNode_S *pstNewNode;
pstNewNode = malloc(sizeof(TreeNode_S));
if (pstNewNode != NULL)
{
pstNewNode->idata = idata;
pstNewNode->pstLeftChild = pstleftchild;
pstNewNode->pstRightChild = pstrightchild;
}
return pstNewNode;
}
/* 销毁树节点 */
void DestroyTreeNode(TreeNode_S *pstTreeNode)
{
if (pstTreeNode != NULL)
{
printf("%d ", pstTreeNode->idata);
free(pstTreeNode);
}
return;
}
/* 销毁树*/
void DestroyTree(TreeHead_S *pstTreeHead)
{
if (pstTreeHead != NULL)
{
if (pstTreeHead->pstLeftChild != NULL)
{
DestroyTree(pstTreeHead->pstLeftChild);
}
if (pstTreeHead->pstRightChild != NULL)
{
DestroyTree(pstTreeHead->pstRightChild);
}
DestroyTreeNode(pstTreeHead);
}
}
/* 获取树的深度 */
int GetTreeDepth(TreeHead_S *pstTreeHead)
{
int l = 0;
int r = 0;
TreeNode_S *pstLeftChild;
TreeNode_S *pstRightChild;
if (pstTreeHead == NULL)
{
return 0;
}
l = 1;
r = 1;
l += GetTreeDepth(pstTreeHead->pstLeftChild);
r += GetTreeDepth(pstTreeHead->pstRightChild);
if (l < r)
{
l = r;
}
return l;
}
/* 前序遍历 */
void Front_Scan(TreeHead_S *pstTreeHead)
{
if (pstTreeHead == NULL)
{
return;
}
printf("%d ",pstTreeHead->idata);
Front_Scan(pstTreeHead->pstLeftChild);
Front_Scan(pstTreeHead->pstRightChild);
return;
}
/* 中序遍历 */
void Middle_Scan(TreeHead_S *pstTreeHead)
{
if (pstTreeHead == NULL)
{
return;
}
Middle_Scan(pstTreeHead->pstLeftChild);
printf("%d ",pstTreeHead->idata);
Middle_Scan(pstTreeHead->pstRightChild);
return;
}
/* 后序遍历 */
void End_Scan(TreeHead_S *pstTreeHead)
{
if (pstTreeHead == NULL)
{
return;
}
End_Scan(pstTreeHead->pstLeftChild);
End_Scan(pstTreeHead->pstRightChild);
printf("%d ",pstTreeHead->idata);
return;
}
int main(void)
{
TreeHead_S *pstTree;
TreeNode_S *pstNode8 = CreateTreeNode(8, NULL, NULL);
TreeNode_S *pstNode7 = CreateTreeNode(7, NULL, NULL);
TreeNode_S *pstNode6 = CreateTreeNode(6, NULL, NULL);
TreeNode_S *pstNode5 = CreateTreeNode(5, NULL, NULL);
TreeNode_S *pstNode4 = CreateTreeNode(4, pstNode8, NULL);
TreeNode_S *pstNode3 = CreateTreeNode(3, pstNode6, pstNode7);
TreeNode_S *pstNode2 = CreateTreeNode(2, pstNode4, pstNode5);
TreeNode_S *pstNode1 = CreateTreeNode(1, pstNode2, pstNode3);
assert((pstNode1 != NULL)&&(pstNode2 != NULL)&&(pstNode3 != NULL)&&
(pstNode4 != NULL)&&(pstNode5 != NULL)&&(pstNode6 != NULL)&&
(pstNode7 != NULL)&&(pstNode8 != NULL));
pstTree = InitTree(pstNode1);
printf("depth:%d\n", GetTreeDepth(pstTree));
printf("front scan: ");
Front_Scan(pstTree);
printf("\nmiddle scan: ");
Middle_Scan(pstTree);
printf("\nend scan: ");
End_Scan(pstTree);
printf("\ndestroy tree: ");
DestroyTree(pstTree);
printf("\n");
return 0;
}