#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct BinaryNode
{
char ch;
struct BinaryNode* lChild;
struct BinaryNode* rChild;
};
void recursion(struct BinaryNode* root)
{
if (root == NULL)
{
return;
}
printf("%c ", root->ch);
recursion(root->lChild);
recursion(root->rChild);
}
void recursion01(struct BinaryNode* root)
{
if (root == NULL)
{
return;
}
recursion(root->lChild);
printf("%c ", root->ch);
recursion(root->rChild);
}
void recursion02(struct BinaryNode* root)
{
if (root == NULL)
{
return;
}
recursion(root->lChild);
recursion(root->rChild);
printf("%c ", root->ch);
}
void calculateLeafNum(struct BinaryNode* root, int * p)
{
if (root == NULL)
{
return;
}
if (root->lChild == NULL && root->rChild == NULL)
{
(*p)++;
}
calculateLeafNum(root->lChild, p);
calculateLeafNum(root->rChild, p);
}
int getTreeHeight(struct BinaryNode * root)
{
if (root == NULL)
{
return 0;
}
int lHeight = getTreeHeight(root->lChild);
int rHeight = getTreeHeight(root->rChild);
int height = lHeight > rHeight ? lHeight + 1 : rHeight + 1;
return height;
}
struct BinaryNode* copyTree(struct BinaryNode * root)
{
if (root == NULL)
{
return NULL;
}
struct BinaryNode* lChild = copyTree(root->lChild);
struct BinaryNode* rChild = copyTree(root->rChild);
struct BinaryNode* newNode = (BinaryNode*)malloc(sizeof(struct BinaryNode));
newNode->lChild = lChild;
newNode->rChild = rChild;
newNode->ch = root->ch;
return newNode;
}
void freeTree(struct BinaryNode* root)
{
if (root == NULL)
{
return;
}
freeTree(root->lChild);
freeTree(root->rChild);
printf("%c被释放了\n", root->ch);
free(root);
}
void test01()
{
struct BinaryNode nodeA = { 'A',NULL,NULL };
struct BinaryNode nodeB = { 'B',NULL,NULL };
struct BinaryNode nodeC = { 'C',NULL,NULL };
struct BinaryNode nodeD = { 'D',NULL,NULL };
struct BinaryNode nodeE = { 'E',NULL,NULL };
struct BinaryNode nodeF = { 'F',NULL,NULL };
struct BinaryNode nodeG = { 'G',NULL,NULL };
struct BinaryNode 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;
printf("二叉树的先序遍历结果为:\n");
recursion(&nodeA);
printf("\n");
printf("二叉树的中序遍历结果为:\n");
recursion01(&nodeA);
printf("\n");
printf("二叉树的后序遍历结果为:\n");
recursion02(&nodeA);
printf("\n");
int num = 0;
calculateLeafNum(&nodeA, &num);
printf("树的叶子数量为:%d\n", num);
int height = getTreeHeight(&nodeA);
printf("树的高度为:%d\n", height);
struct BinaryNode* newTree = copyTree(&nodeA);
printf("拷贝二叉树结果:");
recursion(newTree);
printf("\n");
freeTree(newTree);
}
int main()
{
test01();
system("pause");
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)