二叉树编程
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct BiNode
{
char ch;
struct BiNode *lchild;
struct BiNode *rchild;
};
void cuculateLeafNum(struct BiNode *root,int *p)
{
if (NULL == root)
{
return;
}
if (root->lchild == NULL && root->rchild == NULL)
{
(*p)++;
}
cuculateLeafNum(root->lchild, p);
cuculateLeafNum(root->rchild, p);
}
int getTreeHeight(struct BiNode *root)
{
if (NULL == root)
{
return 0;
}
int lheight = getTreeHeight(root->lchild);
int rheight = getTreeHeight(root->rchild);
int height = lheight > rheight ? lheight + 1 : rheight + 1;
return height;
}
void showBiTree(struct BiNode *root)
{
if (NULL == root)
{
return;
}
printf("%c ",root->ch);
showBiTree(root->lchild);
showBiTree(root->rchild);
}
struct BiNode *copyBiTree(struct BiNode *root)
{
if (NULL == root)
{
return NULL;
}
struct BiNode *lchild = copyBiTree(root->lchild);
struct BiNode *rchild = copyBiTree(root->rchild);
struct BiNode *newnode = malloc(sizeof(struct BiNode));
newnode->lchild = lchild;
newnode->rchild = rchild;
newnode->ch = root->ch;
return newnode;
}
void freeSpace(struct BiNode *root)
{
if (NULL == root)
{
return;
}
freeSpace(root->lchild);
freeSpace(root->rchild);
printf("%c 被释放!\n", root->ch);
free(root);
}
void test()
{
struct BiNode nodeA = { 'A', NULL, NULL };
struct BiNode nodeB = { 'B', NULL, NULL };
struct BiNode nodeC = { 'C', NULL, NULL };
struct BiNode nodeD = { 'D', NULL, NULL };
struct BiNode nodeE = { 'E', NULL, NULL };
struct BiNode nodeF = { 'F', NULL, NULL };
struct BiNode nodeG = { 'G', NULL, NULL };
struct BiNode 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;
cuculateLeafNum(&nodeA, &num);
printf("叶子节点数目:%d\n", num);
int height = getTreeHeight(&nodeA);
printf("树的高度:%d\n",height);
struct BiNode *root = copyBiTree(&nodeA);
showBiTree(root);
printf("\n");
showBiTree(&nodeA);
freeSpace(root);
}
int main(){
test();
system("pause");
return EXIT_SUCCESS;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)