二叉树相关编程(C++)
求二叉树的叶子总数
二叉树的叶子:叶子结点时没有子结点的结点
代码
void calculateleafnum(binarynode* root, int* num)
{
//递归出口
if (root == NULL)
{
return;
}
if (root->Lchild == NULL && root->Rchild == NULL)
{
(*num)++;
}
calculateleafnum(root->Lchild,num);
calculateleafnum(root->Rchild,num);
}
求二叉树的高度
高度是从叶节点数到它的根节点
代码
int getTreeHeight(binarynode* root)
{
if (root == NULL)
{
return 0;
}
//求左子树高度
int Lheight = getTreeHeight(root->Lchild);
int Rheight = getTreeHeight(root->Rchild);
//取左右子树最大值
int height = max(Lheight, Rheight)+1;
return height;
}
二叉树拷贝
代码
//拷贝
binarynode* copyTree(binarynode* root)
{
if (root == NULL)
{
return NULL;
}
//先拷贝左子树
binarynode* Lchlid=copyTree(root->Lchild);
//再拷贝右子树
binarynode* Rchlid = copyTree(root->Rchild);
//创建新节点
binarynode* newnode = new binarynode;
newnode->Lchild = Lchlid;
newnode->Rchild = Rchlid;
newnode->ch = root->ch;
//返回给用户
return newnode;
}
代码清单
#include<iostream>
using namespace std;
struct binarynode
{
char ch;
binarynode* Lchild;
binarynode* Rchild;
};
//统计叶子数量 叶子:没有子节点的结点
void calculateleafnum(binarynode* root, int* num)
{
//递归出口
if (root == NULL)
{
return;
}
if (root->Lchild == NULL && root->Rchild == NULL)
{
(*num)++;
}
calculateleafnum(root->Lchild,num);
calculateleafnum(root->Rchild,num);
}
int getTreeHeight(binarynode* root)
{
if (root == NULL)
{
return 0;
}
//求左子树高度
int Lheight = getTreeHeight(root->Lchild);
int Rheight = getTreeHeight(root->Rchild);
//取左右子树最大值
int height = max(Lheight, Rheight)+1;
return height;
}
//拷贝
binarynode* copyTree(binarynode* root)
{
if (root == NULL)
{
return NULL;
}
//先拷贝左子树
binarynode* Lchlid=copyTree(root->Lchild);
//再拷贝右子树
binarynode* Rchlid = copyTree(root->Rchild);
//创建新节点
binarynode* newnode = new binarynode;
newnode->Lchild = Lchlid;
newnode->Rchild = Rchlid;
newnode->ch = root->ch;
//返回给用户
return newnode;
}
//二叉树遍历
void recursion1(binarynode* root)
{
if (root == NULL)
{
return;
}
//先序遍历,根左右,如上图解
cout << root->ch << " ";
recursion1(root->Lchild);
recursion1(root->Rchild);
}
void test01()
{
binarynode nodea = { 'a',NULL,NULL };
binarynode nodeb = { 'b',NULL,NULL };
binarynode nodec = { 'c',NULL,NULL };
binarynode noded = { 'd',NULL,NULL };
binarynode nodee = { 'e',NULL,NULL };
binarynode nodef = { 'f',NULL,NULL };
binarynode nodeg = { 'g',NULL,NULL };
binarynode nodeh = { 'h',NULL,NULL };
//建立关系
nodea.Lchild = &nodeb;
nodea.Rchild = &nodef;
nodeb.Rchild = &nodec;
nodec.Lchild = &noded;
nodec.Rchild = &nodee;
nodef.Rchild = &nodeg;
nodeg.Lchild = &nodeh;
//求树中叶子的数量
int num=0;
calculateleafnum(&nodea, &num);
cout << "叶子的数量为:" << num<<endl;
//求树的深度
int height= getTreeHeight(&nodea);
cout << "树的高度为:" << height;
}
int main()
{
test01();
return 0;
}