#if 1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _BinaryNode
{
char ch;
struct _BinaryNode *lchild;
struct _BinaryNode *rchild;
}BinaryNode;
//求叶子数量
void calculateLeafNum( 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( BinaryNode * root)
{
if (root == NULL)
{
return 0;
}
int lheight = getTreeHeight(root->lchild);
int rheight = getTreeHeight(root->rchild);
int heigth = lheight > rheight ? lheight + 1 : rheight + 1;
return heigth;
}
//拷贝二叉树
BinaryNode * copyTree( BinaryNode * root)
{
if (root == NULL)
{
return NULL;
}
BinaryNode *lchild = copyTree(root->lchild);
BinaryNode *rchild = copyTree(root->rchild);
BinaryNode *newNode = malloc(sizeof(BinaryNode));
if (newNode == NULL)
{
return NULL;
}
else
{
newNode->ch = root->ch;
newNode->lchild = lchild;
newNode->rchild = rchild;
}
return newNode;
}
//释放二叉树
void freeTree(BinaryNode * root)
{
if (root == NULL)
{
return;
}
freeTree(root->lchild);
freeTree(root->rchild);
free(root);
root = NULL;
}
先序遍历
void recursionDLR(BinaryNode *root)
{
if (root == NULL)
{
return;
}
printf(" %c ", root->ch);
recursionDLR(root->lchild);
recursionDLR(root->rchild);
}
中序遍历
void recursionLDR(BinaryNode *root)
{
if (root == NULL)
{
return;
}
recursionLDR(root->lchild);
printf(" %c ", root->ch);
recursionLDR(root->rchild);
}
后序遍历
void recursionLRD(BinaryNode *root)
{
if (root == NULL)
{
return;
}
recursionLRD(root->lchild);
recursionLRD(root->rchild);
printf(" %c ", root->ch);
}
入口函数
int main(int argc, char *argv[])
{
BinaryNode nodeA = { 'A', NULL, NULL };
BinaryNode nodeB = { 'B', NULL, NULL };
BinaryNode nodeC = { 'C', NULL, NULL };
BinaryNode nodeD = { 'D', NULL, NULL };
BinaryNode nodeE = { 'E', NULL, NULL };
BinaryNode nodeF = { 'F', NULL, NULL };
BinaryNode nodeG = { 'G', NULL, NULL };
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("======xin============\n");
printf("先序遍历:");
recursionDLR(&nodeA);
printf("\n中序遍历:");
recursionLDR(&nodeA);
printf("\n后序遍历:");
recursionLRD(&nodeA);
printf("\n");
int num = 0;
calculateLeafNum(&nodeA, &num);
printf("叶子数量为:%d\n", num);
int height = getTreeHeight(&nodeA);
printf("树高度为:%d\n", height);
BinaryNode * newRoot = copyTree(&nodeA);
printf("======xin============\n");
printf("先序遍历:");
recursionDLR(&nodeA);
printf("\n中序遍历:");
recursionLDR(&nodeA);
printf("\n后序遍历:");
recursionLRD(&nodeA);
printf("\n");
freeTree(newRoot);
system("pause");
return 0;
}
#endif