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;
}

猜你喜欢

转载自blog.csdn.net/qq_39016425/article/details/84177882