#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Binary {
char ch;
struct Binary* Lchild;
struct Binary* Rchild;
};
//计算二叉树的叶子结点数量
void calculuteLeafNum(struct Binary* root, int* pNum) {
if (root == NULL)
return;
if (root->Lchild == NULL && root->Rchild == NULL) {
(*pNum)++;
}
calculuteLeafNum(root->Rchild, pNum);
calculuteLeafNum(root->Lchild, pNum);
}
//求树的高度/深度
int getTreeHeight(struct Binary* root) {
if (root == NULL)
return 0;
int lHeight = getTreeHeight(root->Lchild);
int rHeight = getTreeHeight(root->Rchild);
return lHeight > rHeight ? lHeight + 1 : rHeight + 1;
}
//拷贝二叉树
struct Binary* copyTree(struct Binary* root) {
if (root == NULL)
return NULL;
//先拷贝左子树
struct Binary* lChild = copyTree(root->Lchild);
//再拷贝右子树
struct Binary* rChild = copyTree(root->Rchild);
//在创建一个根节点
struct Binary* newNode = malloc(sizeof(struct Binary));
newNode->ch = root->ch;
newNode->Lchild = lChild;
newNode->Rchild = rChild;
return newNode;
}
//树的遍历
void recursion(struct Binary* root) {
if (root == NULL)
return;
printf("%c ", root->ch);
recursion(root->Lchild);
recursion(root->Rchild);
}
//二叉树的释放
void freeTree(struct Binary* root) {
if (root == NULL)
return;
freeTree(root->Lchild);
freeTree(root->Rchild);
free(root);
}
void test01() {
struct Binary nodeA = { 'A',NULL,NULL };
struct Binary nodeB = { 'B',NULL,NULL };
struct Binary nodeC = { 'C',NULL,NULL };
struct Binary nodeD = { 'D',NULL,NULL };
struct Binary nodeE = { 'E',NULL,NULL };
struct Binary nodeF = { 'F',NULL,NULL };
struct Binary nodeG = { 'G',NULL,NULL };
struct Binary nodeH = { 'H',NULL,NULL };
//建立关系
nodeA.Lchild = &nodeB;
nodeA.Rchild = &nodeF;
nodeB.Rchild = &nodeC;
nodeC.Lchild = &nodeD;
nodeC.Rchild = &nodeE;
nodeF.Rchild = &nodeG;
nodeG.Lchild = &nodeH;
//计算二叉树的叶子结点数量
int num = 0;
calculuteLeafNum(&nodeA, &num);
printf("二叉树的叶子结点数量为:%d\n", num);
//求树的高度/深度
int height = getTreeHeight(&nodeA);
printf("二叉树的高度为:%d\n", height);
//树的拷贝
struct Binary* newTree = copyTree(&nodeA);
//树的遍历
recursion(newTree);
//释放二叉树
freeTree(newTree);
}
int main()
{
test01();
system("pause");
return EXIT_SUCCESS;
}
C语言实现二叉树的遍历,拷贝等操作
最新推荐文章于 2024-06-06 22:37:24 发布