数据结构-二叉树编程

求二叉树叶子数量

如果节点的左子树与右子树相同且为NULL

int num=0;
void GetLeavesNum(BN* a)
{
if (a == NULL)
return;
if (a->lchild == NULL && a->rchild == NULL)
{
num++;
}
GetLeavesNum(a->lchild);
GetLeavesNum(a->rchild);
}

求二叉树的高度

左子树和右子树取最大值再加一就是这棵树的高度

int GetTreeHeight(BN* a)
{
if (a == NULL)
return 0;

//获取左子树高度
int lHeight = GetTreeHeight(a->lchild);
//获取右子树高度
int rHeight = GetTreeHeight(a->rchild);
if (lHeight > rHeight)
{
return lHeight + 1;
}
else if(rHeight>lHeight)
{
return rHeight + 1;
}
else
{
return lHeight+1;
}
}

拷贝二叉树

BN* CopyBinaryTree(BN* a)
{
if (a == NULL)
{
return NULL;
}
//BN*test = (BN*)malloc(sizeof(BN));
//test->ch = a->ch;
//test->lchild = a->lchild;
//test->rchild = a->rchild;
BN*lchild = CopyBinaryTree(a->lchild);
BN*rchild = CopyBinaryTree(a->rchild);
BN* test = (BN*)malloc(sizeof(BN));
test->ch = a->ch;
test->lchild = lchild;
test->rchild = rchild;
return test;
}

释放二叉树

void DeleteBinaryTree(BN* a)
{
if (a == NULL)
{
return;
}
//先删除左
DeleteBinaryTree(a->lchild);
//再删除右
DeleteBinaryTree(a->rchild);
delete(a);
a = NULL;
}