C/C++语言之二叉树

源代码:

#include <iostream>
#include<stdlib.h>
using namespace std;
typedef struct node
{
	char data;
	struct node *Ltree, *Rtree;
}trees,*ptrees;
ptrees create_tree()
{
	ptrees p=new node();
	char a;
	cin >> a;
	if (a == '0')
	{
		p = NULL;
	}
	else
	{
		p->data = a;
		p->Ltree=create_tree();
		p->Rtree = create_tree();
	}
	return p;
}
void pre_tree(ptrees p)
{
	if(p)
	{
		cout <<p->data;
		pre_tree(p->Ltree);
		pre_tree(p->Rtree);
		
	}
}
void in_tree(ptrees p)
{
	if (p)
	{
		
		pre_tree(p->Ltree);
		cout << p->data;
		pre_tree(p->Rtree);

	}
}
void post_tree(ptrees p)
{
	if (p)
	{
		
		pre_tree(p->Ltree);
		pre_tree(p->Rtree);
		cout << p->data;

	}
}
static int cnt = 0;
void LeafCountNode(ptrees p){  //统计叶子结点个数  
	if (p){
		if (p->Ltree == NULL && p->Rtree == NULL)
		{
			cnt+=1;
		}
	      LeafCountNode(p->Ltree);
	      LeafCountNode(p->Rtree);
	}	
	
}
void IInOrder(ptrees p){ //输出各个叶子结点值  
	if (p){
		
		if (!p->Ltree && !p->Rtree)
			printf("%c ", p->data);
		IInOrder(p->Ltree);
		IInOrder(p->Rtree);
	}
}
int PostTreeDepth(ptrees p){       //求树的高度  
	int h1, h2, h;
	if (p == NULL){
		return 0;
	}
	else{
		h1 = PostTreeDepth(p->Ltree);
		h2 = PostTreeDepth(p->Rtree);
		h = (h1>h2 ? h1 : h2) + 1;
		return h;
	}
}	
void OutPutPath(ptrees p, char path[], int len){      //输出每个叶子结点到根节点的路径  
	if (p){
		if (!p->Ltree && !p->Rtree){
			printf("%c ", p->data);
			for (int i = len - 1; i >= 0; i--)
				printf("%c ", path[i]);
			printf("\n");
		}
		path[len] = p->data;
		OutPutPath(p->Ltree, path, len + 1);
		OutPutPath(p->Rtree, path, len + 1);
	}
}

int main()
{
	ptrees p;
	p=create_tree();
	cout << "先序遍历元素为:"<<endl;
	pre_tree(p);
	cout << "中序遍历元素为:"<<endl;
	in_tree(p);
	cout << "后序遍历元素为:" <<endl;
	post_tree(p);
	cout << endl;
	LeafCountNode(p);
	cout << endl;
	IInOrder(p);
	cout<< endl;
	cout << cnt << endl;
	char path[20];
	int len = 15;
	OutPutPath(p, path, len);

	
	system("PAUSE");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值