二叉树的基本操作

本文介绍了一种使用C++实现二叉树的方法,并详细展示了如何通过递归方式创建、遍历二叉树,包括前序、中序遍历等。此外,还介绍了计算树的深度、节点数量及叶子节点数量的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

class btree
{
public:
	int value;
	btree *lchild;
	btree *rchild;	
};
btree * createbtree(btree * root,int *num,int &index)  //前序递归创建树
{
	if(num[index]==0)
	{
		return NULL;
	}
	root = new btree;
	root->value=num[index];
	root->lchild = createbtree(root->lchild,num,++index);
	root->rchild = createbtree(root->rchild,num,++index);
	return root;
}
void pre(btree *root)   //前序输出
{
	if(root==NULL)
		return ;
	cout<<root->value<<" ";
	pre(root->lchild);
	pre(root->rchild);
}
void in(btree *root)  //中序输出
{
	if(root==NULL)
		return ;
	
	in(root->lchild);
	cout<<root->value<<" ";
	in(root->rchild);
}
void print(btree *root,int h)
{
    if(root != NULL)
    {
        print(root -> rchild,h+1);
        for(int i=0; i<h; i++)
            cout << "   ";
        cout << root -> value;
        print(root -> lchild,h+1);
    }
    cout << endl;
}
int deep(btree *root)  //树的深度
{
	int l,r;
	if(root==NULL)
		return 0;
	l = deep(root->lchild);
	r = deep(root->rchild);
	return max(l,r)+1;
}
int sum(btree *root)   //节点个数
{
	int l,r;
	if(root==NULL)
		return 0;
	l = sum(root->lchild);
	r = sum(root->rchild);
	return l+r+1;
}
void change(btree * & root)  //交换左右节点
{
	if(root==NULL)
		return ;
	btree *t;
	t=root->lchild;
	root->lchild = root->rchild;
	root->rchild = t;
	change(root->lchild);
	change(root->rchild);
}
void getleaves(btree *root,int &ans)   //求叶子节点的个数 
{
	if(root==NULL)
		return ;
	if(root->lchild==NULL&&root->rchild==NULL)
	{
		ans++;
		return ;
	}
	getleaves(root->lchild,ans);
	getleaves(root->rchild,ans);
}
int main()
{
	queue<btree *> aqueue;
	int index=0;
	int num[]={1,2,4,8,100,0,0,0,9,0,0,5,10,0,0,11,0,0,3,6,12,0,0,13,0,0,7,14,0,0,15,0,0};
	btree *root=NULL;
	root = createbtree(root,num,index);
	pre(root);cout<<endl;
	in(root);cout<<endl;
	cout<<deep(root)<<endl;
	cout<<sum(root)<<endl;
	print(root,1);
	change(root);
	print(root,1);
	aqueue.push(root);
	while(!aqueue.empty())
	{
		btree *temp = aqueue.front();
		cout<<temp->value<<" ";
		aqueue.pop();
		if(temp->lchild!=NULL)
			aqueue.push(temp->lchild);
		if(temp->rchild!=NULL)
			aqueue.push(temp->rchild);
	}
	cout<<endl;
	int ans=0;
	getleaves(root,ans);
	cout<<ans<<endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值