二叉树的简单应用

#include<iostream>
#include<stdlib.h>
using namespace std;

typedef struct node{
	int data;
	struct node *left,*right;
}BTNode;

BTNode *CreateBTree(int a[],int n)
{
	BTNode *root,*c,*p,*q;
	root=(BTNode *)malloc(sizeof(BTNode));//单独处理根结点 
	root->data=a[0];
	root->left=root->right=NULL;
	for(int i=1;i<n;i++){//建立链接其他结点 
		p=(BTNode *)malloc(sizeof(BTNode));
		p->data=a[i];
		p->left=p->right=NULL;
		c=root;
		while(c){//找到要插入的位置 
		q=c;
		if(c->data>p->data){//比当前根结点小,从左子树进入 
			c=c->left;
			}
		else{//比当前根结点大,从右子树进入 
			c=c->right;
			}
		}
		if(q->data>p->data){//待插入结点比尾结点的值小,链接在左边 
			q->left=p;
		}
		else{
			q->right=p;
		}
	}
	return root;
}

int LeafCount(BTNode *root)
{
		int L1,L2; 
		if(!root){
			return 0;
		}
		else{
			L1=LeafCount(root->left);//递归遍历左子树 
			L2=LeafCount(root->right);//递归遍历右子树 
			if(!root->left&&!root->right){//判断是否为叶子结点 
				return L1+L2+1;//是的话,加一 
			}
			else{
				return L1+L2;//不是加0 
			}/*return L1+L2+(!root->left&&!root->right)*/
		}
}

int ParentCount(BTNode *root)
{
		int L1,L2; 
		if(!root){
			return 0;
		}
		else{
			L1=ParentCount(root->left);//递归遍历左子树 
			L2=ParentCount(root->right);//递归遍历右子树 
			if(root->left&&root->right){//判断是否为双分支结点 
				return L1+L2+1;//是的话,加一 
			}
			else{
				return L1+L2;//不是加0 
			}
		}
}

int LevelCount(BTNode *root)
{
	int L1,L2;
	if(!root){
		return 0;
	}
	else{
		L1=LevelCount(root->left);
		L2=LevelCount(root->right);
		return L1>L2?L1+1:L2+1;//判断两者谁大,大的一方加一 
	}
}

void MirrorBTree(BTNode *root)
{
	BTNode *t;
	if(root){
		t=root->left;
		root->left=root->right;
		root->right=t;
		MirrorBTree(root->left);
		MirrorBTree(root->right);
	}
} 

void PreOrder(BTNode *root)
{
	if(root){
	cout<<root->data<<" ";
	PreOrder(root->left);
	PreOrder(root->right);
	}
} 
int main()
{
	int n,cnt;
	cout<<"请输入数组长度n:";
	cin>>n;
	int *a;
	a=(int *)malloc(n*sizeof(int));
	cout<<"请输入数组元素:";
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	BTNode *root;
	//建立二叉排序树 
	root=CreateBTree(a,n);
	cnt=LeafCount(root);//求叶子结点个数 
	cout<<cnt<<endl;
	cnt=ParentCount(root);//求双分支结点个数
	cout<<cnt<<endl; 
	cnt=LevelCount(root);
	cout<<cnt<<endl;
	MirrorBTree(root);//镜像树
	PreOrder(root);//前序遍历验证是否转为镜像树 
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值