二叉树的前序,中序,后序遍历本质上是深度优先搜索DFS,可以用过递归方法实现,求二叉树的高度,求二叉树叶子的个数,拷贝二叉树和删除二叉树,都可以通过递归的方式实现
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct BINARYNODE
{
char ch;
struct BINARYNODE* lchild;
struct BINARYNODE* rchild;
}BinaryNode;
void Recursion(BinaryNode* root)
{
if (root == NULL)
return;
printf("%c", root->ch);
Recursion(root->lchild);
Recursion(root->rchild);
}
void CalculateLeafNum(BinaryNode* root,int* leafNum)
{
if (root == NULL)
return;
if (root->lchild == NULL && root->rchild == NULL)
{
(*leafNum)++;
}
CalculateLeafNum(root->lchild,leafNum);
CalculateLeafNum(root->rchild,leafNum);
}
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 : RightDepth) + 1;
return depth;
}
// 拷贝二叉树
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 FreeSpaceBinaryTree(BinaryNode* root)
{
if (root == NULL)
return;
FreeSpaceBinaryTree(root->lchild);
FreeSpaceBinaryTree(root->rchild);
free(root);
}
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;
int depth = 0;
CalculateLeafNum(&node1,&leafNum);
printf("%d\n", leafNum);
depth = CaculateTreeDepth(&node1);
printf("%d\n", depth);
BinaryNode* root = CopyBinaryTree(&node1);
Recursion(root);
printf("\n");
FreeSpaceBinaryTree(root);
}
int main()
{
CresteBinaryTree();
system("pause");
return 0;
}