#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
typedef struct BINARYNODE {
char ch;
struct BINARYNODE* lchild;
struct BINARYNODE* rchild;
}BinaryNode;
BinaryNode* CopyBinaryTree(BinaryNode* root) {
if (root == NULL) return NULL;
BinaryNode* lchild = CopyBinaryTree(root->lchild);
BinaryNode* rchild = CopyBinaryTree(root->rchild);
BinaryNode* newnode = (BinaryNode*)malloc(sizeof(BinaryNode));
newnode->ch = root->ch;
newnode->lchild = lchild;
newnode->rchild = rchild;
return newnode;
}
void FreeSpaceBinary(BinaryNode* root) {
if (root == NULL) return;
FreeSpaceBinary(root->lchild);
FreeSpaceBinary(root->rchild);
free(root);
}
int CaculateTreeDepth(BinaryNode* root) {
if (root == NULL) {
return 0;
}
int depth = 0;
int leftDepth = CaculateTreeDepth(root->lchild);
int rightDepth = CaculateTreeDepth(root->rchild);
depth = leftDepth > rightDepth ? leftDepth + 1: rightDepth + 1;
return depth;
}
void CaculateLeafNum(BinaryNode* root,int* leafNum) {
if (root == NULL) return;
if (root->rchild == NULL && root->lchild == NULL) {
(*leafNum)++;
}
CaculateLeafNum(root->lchild, leafNum);
CaculateLeafNum(root->rchild, leafNum);
}
void Recursion(BinaryNode* root)
{
if (root == NULL)
return;
Recursion(root->lchild);
Recursion(root->rchild);
printf("%c", root->ch);
}
void CresteBinaryTree() {
BinaryNode node1 = { 'A',NULL,NULL };
BinaryNode node2 = { 'B',NULL,NULL };
BinaryNode node3 = { 'C',NULL,NULL };
BinaryNode node4 = { 'D',NULL,NULL };
BinaryNode node5 = { 'E',NULL,NULL };
BinaryNode node6 = { 'F',NULL,NULL };
BinaryNode node7 = { 'G',NULL,NULL };
BinaryNode node8 = { 'H',NULL,NULL };
node1.lchild = &node2;
node1.rchild = &node6;
node2.rchild = &node3;
node3.lchild = &node4;
node3.rchild = &node5;
node6.rchild = &node7;
node7.lchild = &node8;
Recursion(&node1);
printf("\n");
int leafNum = 0;
CaculateLeafNum(&node1,&leafNum);
printf("叶子节点的数目:%d\n", leafNum);
std::cout << CaculateTreeDepth(&node1)<<std::endl;
BinaryNode* root = CopyBinaryTree(&node1);
Recursion(root);
}
int main() {
CresteBinaryTree();
system("pause");
return 0;
}