二叉树相关代码

#include <iostream>
using namespace std;
int n = 0; 
int sum = 0;
struct Bnode{
	int data;
	Bnode *lch;
	Bnode *rch;	
};
Bnode*creat(){
	Bnode *p;
	int x;
	cin >> x;
	if(x == 0) p = NULL;
	else{
		p = new(Bnode);
		p -> data = x;
		p -> lch = creat();
		p -> rch = creat();
	}
	return p;	
};
void firstF(Bnode *p){
	if(p == NULL) return;
	else{
		cout << p ->data << endl;
		firstF(p ->lch);
		firstF(p ->rch);
	}
}
void midF(Bnode *p){
	if(p == NULL) return;
	else{
		firstF(p ->lch);
		cout << p ->data << endl;
		firstF(p ->rch);
	}
}
void enF(Bnode *p){
	if(p == NULL) return;
	else{
		firstF(p ->lch);
		firstF(p ->rch);
		cout << p ->data << endl;
	}
}
void leaf(Bnode *p){
	if(p != NULL){
		if(p ->lch == NULL && p ->rch == NULL)
	 		n++;
		leaf(p ->lch);
		leaf(p ->rch);			
	}

}
int dep(Bnode *p){
	if(p == NULL) return 0;
	else{
		int d1 = dep(p ->lch);
		int d2 = dep(p ->rch);
		return 1+(d1>d2?d1:d2);
	}
}
void num(Bnode *p){
	if(p != NULL){
		sum++;
		num(p ->lch);
		num(p ->rch);
	}
}
int main(){
	Bnode *h;
	h = creat();
	printf("这是先序遍历:\n");
	firstF(h);
	printf("这是中序遍历:\n");
	midF(h);
	printf("这是后序遍历:\n");
	enF(h);
	leaf(h);
	printf("共有%d片叶子!\n",n);
	int dp = dep(h); 
	printf("树深:%d\n",dp);
	num(h);
	printf("%d\n",sum);
	return 0;
}
/*
1
2
4
0
0
0
3
5
0
7
0
0
6
8
0
0
9
0
0
×/ 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值