版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z861269429/article/details/51778045
给定二叉树的数据类型如下
typedef char Element;
struct Node
{
Element data;
struct Node *lchild;
struct Node *rchild;
};
typedef struct Node BTNode;
typedef struct Node * BTree;
①二叉树输出
完成void PrintBTree(BTree root)函数,该函数输出二叉树的广义表表示。
void PrintBTree(BTree root)
{
if(root==NULL)return;
printf("%c",root‐>data);
if(root‐>lchild==NULL&&root‐>rchild==NULL)
return;
printf("(");
if(root‐>lchild!=NULL)
PrintBTree(root‐>lchild);
printf(",");
if(root‐>rchild!=NULL)
PrintBTree(root‐>rchild);
printf(")");
}
②二叉树输出叶节点
完成void PrintLeaf(BTree root)函数,该函数按先序遍历的方式输出二叉树所有的叶节点。
void PrintLeaf(BTree root)
{
if(root==NULL)return;
if(root‐>lchild==NULL&&root‐>rchild==NULL)
printf("%c\n",root‐>data);
PrintLeaf(root‐>lchild);
PrintLeaf(root‐>rchild);
}
③二叉树叶节点数
完成int GetLeafNum(BTree root);函数,该函数统计二叉树root中叶节点数目并返回该值。
int GetLeafNum(BTree root)
{
if(root==NULL)
return 0;
if(root‐>lchild==NULL&&root‐>rchild==NULL)
return 1;
return GetLeafNum(root‐>lchild)+GetLeafNum(root‐>rchild);
}
④二叉树树深
完成int GetDepth(BTree root)函数,该函数返回二叉树root的树深。
int GetDepth(BTree root)
{
int ldepth,rdepth;
if(root==NULL)
return 0;
rdepth=GetDepth(root‐>rchild);
ldepth=GetDepth(root‐>lchild);
return (rdepth>ldepth?rdepth:ldepth)+1;
}
⑤二叉树节点数
完成int GetNum(BTree root)函数,该函数统计二叉树root中节点数目并返回该值。
int GetNum(BTree root)
{
int num;
if(root==NULL)
return 0;
num=1;
if(root‐>lchild!=NULL)
num+=GetNum(root‐>lchild);
if(root‐>rchild!=NULL)
num+=GetNum(root‐>rchild);
return num;
}
⑥二叉树销毁
完成BTree Dispose(BTree root)函数,该函数销毁二叉树并返回NUL指针。
BTree Dispose(BTree root)
{
if(root==NULL)
return NULL;
Dispose(root‐>lchild);
Dispose(root‐>rchild);
free(root);
return NULL;
}