#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct BiNode
{
int data;
struct BiNode *lchild, *rchild;
}BiNode,*BiTree;
//先序遍历
void preOrder(BiNode *root)
{
if (root != NULL)
{
printf("%d",root->data);
preOrder(root->lchild);
preOrder(root->rchild);
}
}
//中序遍历
void inOrder(BiNode *root)
{
if (root != NULL)
{
inOrder(root->lchild);
printf("%d", root->data);
inOrder(root->rchild);
}
}
//后序遍历
void postOrder(BiNode *root)
{
if (root != NULL)
{
postOrder(root->lchild);
postOrder(root->rchild);
printf("%d", root->data);
}
}
//计算叶子结点
void CountLeafNum(BiNode *root, int *num)
{
if (root != NULL)
{
if (!root->lchild&&!root->rchild)
{
(*num)++;
printf("%d", root->data);
}
CountLeafNum(root->lchild,num);
CountLeafNum(root->rchild,num);
}
}
//计算深度
int GetDepth(BiNode *root)
{
int ldepth = 0, rdepth = 0;
int depthVal = 0;
if (root == NULL)
{
return depthVal;
}
ldepth = GetDepth(root->lchild);//求出左子树深度
rdepth = GetDepth(root->rchild);//求出右子树深度
depthVal = 1 + ((ldepth > rdepth) ? ldepth : rdepth);//左右子树最大深度 + 1 即为树的最大深度。
return depthVal;
}
//拷贝树
BiNode *Copy_tree(BiNode *root)
{
BiNode *tmp = NULL;
if (root != NULL)
{
tmp = (BiNode *)malloc(sizeof(BiNode));
tmp->data = root->data;
tmp->lchild = Copy_tree(root->lchild);
tmp->rchild = Copy_tree(root->rchild);
}
return tmp;
}
void main01()
{
BiNode t1, t2, t3, t4, t5;
memset(&t1, 0, sizeof(BiNode));
memset(&t2, 0, sizeof(BiNode));
memset(&t3, 0, sizeof(BiNode));
memset(&t4, 0, sizeof(BiNode));
memset(&t5, 0, sizeof(BiNode));
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;
preOrder(&t1);
inOrder(&t1);
postOrder(&t1);
}
void main()
{
int num = 0;
BiTree p1, p2, p3, p4, p5;
p1 = (BiTree)malloc(sizeof(BiNode));
p2 = (BiTree)malloc(sizeof(BiNode));
p3 = (BiTree)malloc(sizeof(BiNode));
p4 = (BiTree)malloc(sizeof(BiNode));
p5 = (BiTree)malloc(sizeof(BiNode));
memset(p1, 0, sizeof(BiNode));
memset(p2, 0, sizeof(BiNode));
memset(p3, 0, sizeof(BiNode));
memset(p4, 0, sizeof(BiNode));
memset(p5, 0, sizeof(BiNode));
p1->data = 1;
p2->data = 2;
p3->data = 3;
p4->data = 4;
p5->data = 5;
p1->lchild = p2;
p1->rchild = p3;
p2->lchild = p4;
p3->lchild = p5;
preOrder(p1);
inOrder(p1);
postOrder(p1);
CountLeafNum(p1, &num);
printf("num:%d", num);
printf("树的高度为:%d", GetDepth(p1));
preOrder(Copy_tree(p1));
inOrder(Copy_tree(p1));
postOrder(Copy_tree(p1));
}
树的简单遍历、深度、叶子数量、拷贝
最新推荐文章于 2023-10-05 18:30:00 发布