求叶子节点个数,树的高度,拷贝二叉树
/*
1
2 3
4 5
*/
typedef struct BiTNode
{
int data;
struct BiTNode *lchild, *rchild; //左孩子 右孩子
}BiTNode, *BiTree;
void PreOrder(BiTNode *T)
{
if (T != NULL)
{
printf("%d ", T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BiTNode *T)
{
if (T != NULL)
{
InOrder(T->lchild);
printf("%d ", T->data);
InOrder(T->rchild);
}
}
void PostOrder(BiTNode *T)
{
if (T != NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
printf("%d ", T->data);
}
}
//求二叉树的叶子节点个数:左右节点都为空的
void GetLeafCount(BiTNode *T,int *count)
{
if (T != NULL)
{
if (T->lchild == NULL &&T->rchild == NULL)
{
(*count)++;
}
GetLeafCount(T->lchild, count);
GetLeafCount(T->rchild, count);
}
}
//求二叉树的高度(深度)(几层):
//也是递归求解,左右子树的高度中的比较高的加上根节点就是树的高度
int GetDepth(BiTNode *T)
{
int ndepth = 0, ldepth = 0, rdepth = 0;
if (!T)
{
return 0;
}
ldepth = GetDepth(T->lchild);
rdepth = GetDepth(T->rchild);
ndepth = 1 + (ldepth > rdepth ? ldepth : rdepth);
return ndepth;
}
//拷贝二叉树
BiTNode * copyTree(BiTNode *T)
{
if (!T)
{
return NULL;
}
BiTNode *newbit = NULL, *lptr = NULL, *rptr = NULL;
if (T->lchild)
{
lptr = copyTree(T->lchild);
}
else
{
lptr = NULL;
}
if (T->rchild)
{
rptr = copyTree(T->rchild);
}
else
{
rptr = NULL;
}
newbit = (BiTNode *)malloc(sizeof(BiTNode));
newbit->lchild = lptr;
newbit->rchild = rptr;
newbit->data = T->data;
return newbit;
}
void main()
{
BiTNode b1, b2, b3, b4, b5;
memset(&b1, 0, sizeof(BiTNode));
memset(&b2, 0, sizeof(BiTNode));
memset(&b3, 0, sizeof(BiTNode));
memset(&b4, 0, sizeof(BiTNode));
memset(&b5, 0, sizeof(BiTNode));
b1.data = 1;
b2.data = 2;
b3.data = 3;
b4.data = 4;
b5.data = 5;
//构建树关系
b1.lchild = &b2;
b1.rchild = &b3;
b2.lchild = &b4;
b3.lchild = &b5;
printf("\n先根遍历");
PreOrder(&b1);
printf("\n中根遍历");
InOrder(&b1);
printf("\n后根遍历");
PostOrder(&b1);
cout << endl;
int ncount = 0;
GetLeafCount(&b1, &ncount);
cout << ncount << endl;
cout << "深度:" << GetDepth(&b1) << endl;
printf("\n中根遍历");
BiTNode *T2 = copyTree(&b1);
InOrder(T2);
system("pause");
}
结果;