// 树的遍历.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdlib.h>
//二叉链表示法
typedef struct BiTNode
{
int data;
BiTNode *lchild, *rchild;
};
typedef struct BiTNode* Bitree;
//先序遍历
void PreOder(BiTNode *root)
{
if (root==NULL)
{
return;
}
printf("%d ",root->data);
//遍历左子树
PreOder(root->lchild);
//遍历右子树
PreOder(root->rchild);
}
//中序遍历
void InOrder(BiTNode *root)
{
if (root == NULL)
{
return;
}
//遍历左子树
InOrder(root->lchild);
printf("%d ", root->data);
//遍历右子树
InOrder(root->rchild);
}
//后序遍历
void PostOrder(BiTNode *root)
{
if (root == NULL)
{
return;
}
//遍历左子树
PostOrder(root->lchild);
//遍历右子树
PostOrder(root->rchild);
printf("%d ", root->data);
}
//计算二叉树中叶子结点的数目
int num = 0;
void LeafCount(BiTNode *root)
{
if (root!=NULL)
{
if (root->lchild ==NULL&&root->rchild==NULL)
{
num++;
printf("%d\n",root->data);
}
LeafCount(root->lchild);
LeafCount(root->rchild);
}
//return 0;
//printf("%d\n ", num);
}
//计算二叉树的深度
int DepthTree(BiTNode *root)
{
int leftDepth = 0;
int rightDepth = 0;
int depth = 0;
if (root==NULL)
{
depth = 0;
return depth;
}
//求左子树高度
leftDepth = DepthTree(root->lchild);
//求右子树高度
rightDepth = DepthTree(root->rchild);
//+1
depth = 1+(leftDepth > rightDepth ? leftDepth : rightDepth);
return depth;
}
//copy二叉树
BiTNode* CopyTree(BiTNode* root)
{
BiTNode* newNode;
BiTNode* newLeftNode;
BiTNode* newRightNode;
if (root==NULL)
{
return NULL;
}
if (root->lchild!=NULL)
{
newLeftNode = CopyTree(root->lchild);
}
else
{
newLeftNode = NULL;
}
if (root->rchild != NULL)
{
newRightNode = CopyTree(root->rchild);
}
else
{
newRightNode = NULL;
}
newNode = (BiTNode*)malloc(sizeof(BiTNode));
if (newNode == NULL)
{
return NULL;
}
newNode->lchild = newLeftNode;
newNode->rchild = newRightNode;
newNode->data = root->data;
return newNode;
}
int main()
{
BiTNode t1, t2, t3, t4, t5;
memset(&t1,0,sizeof(BiTNode));
memset(&t2, 0, sizeof(BiTNode));
memset(&t3, 0, sizeof(BiTNode));
memset(&t4, 0, sizeof(BiTNode));
memset(&t5, 0, sizeof(BiTNode));
t1.data = 1;
t2.data = 2;
t3.data = 3;
t4.data = 4;
t5.data = 5;
t1.lchild = &t2;
t1.rchild = &t3;
t2.lchild = &t4;
t3.lchild = &t5;
PreOder(&t1);
printf("\npre\n");
InOrder(&t1);
printf("\nin\n");
PostOrder(&t1);
printf("\npost\n");
//system("pause");
LeafCount(&t1);
printf("叶子结点个数 %d\n",num);
printf("树的高度: %d\n", DepthTree(&t1));
BiTNode* root = CopyTree(&t1);
PreOder(root);
printf("\npre\n");
system("pause");
return 0;
}
树的应用-树的叶子结点数、树的深度、树的拷贝
最新推荐文章于 2022-07-30 16:33:05 发布