数据结构--二叉树及其一些操作

博前感想:

二叉树也是数据结构中非常中非常重要的一种结构,特别是在当前大数据的时候,二叉树的存储和查找排序算法显得尤为重要。

下面是代码块:

#include<stdio.h>
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
using namespace std;

typedef struct Node
{
	Node *lc, *rc;
	char data;

}node,*binary_tree;

void create(binary_tree &h)
{
	char ch;
	cin >> ch;
	if (ch == '%')
	{
		h = NULL;
	}
	else
	{
		h = new Node;
		h->data = ch;
		create(h->lc);
		create(h->rc);
	}
}

void preorder(binary_tree h)
{
	if (h)
	{
		cout << h->data<<" ";
		preorder(h->lc);
		preorder(h->rc);
	}
	//cout << endl;
}

int get_depth(binary_tree h)
{
	if (h == NULL)
	{
		return 0;
	}
	int l_depth = 1 + get_depth(h->lc);
	int r_depth = 1 + get_depth(h->rc);
	int max_depth = l_depth > r_depth ? l_depth : r_depth;
	return max_depth;
}

int get_leaves(binary_tree h)
{
	if(h==NULL)              //顺序不能换
	{
		return 0;
	}
	if (h->lc == NULL && h->rc == NULL)
	{
		return 1;
	}

	return get_leaves(h->lc) + get_leaves(h->rc);
}

int get_nodenum(binary_tree h)        //获取总的节点数
{
	if (h == NULL)
	{
		return 0;
	}
	//if (h != NULL)//&&(h->lc!=NULL||h->rc!=NULL))
	//{
	//	return 1;
	//}
	return get_nodenum(h->lc) + get_nodenum(h->rc)+1;
}

int get_mid_nodenum(binary_tree h)    //获取中间节点数
{
	get_nodenum(h);
	get_leaves(h);
	//int mid_node_sum;
	//if (h == NULL)
	//{
	//	return 0;
	//}
	//if (!(h->lc == NULL && h->rc == NULL))
	//{
	//	 
	//}
	get_mid_nodenum(h->lc)++;
	get_mid_nodenum(h->rc)++;
	int l_mid_node_num = get_mid_nodenum(h->lc) ;
	int r_mid_node_num = get_mid_nodenum(h->rc) ;
	= l_mid_node_num + r_mid_node_num+1 ;
	//return get_mid_nodenum(h->lc) + get_mid_nodenum(h->rc);
	return get_nodenum(h) - get_leaves(h);
}

void mirror(binary_tree h)
{
	if (h == NULL)
	{
		return;
	}
	binary_tree t = h->lc;
	h->lc = h->rc;
	h->rc = t;
	mirror(h->lc);
	mirror(h->rc);
}

int main()
{
	binary_tree hwq;
	create(hwq);
	cout << "先序遍历为:" << endl;
	preorder(hwq);
	cout << endl;
	cout <<"叶子数为:" << get_leaves(hwq) <<endl;
	cout << "树的深度为:" << get_depth(hwq) << endl;
	cout << "节点数为:" << get_nodenum(hwq) << endl;
	cout << "中间节点数为:" << get_mid_nodenum(hwq) << endl;
	mirror(hwq);
	cout << "镜像后的二叉树先序遍历为:" << endl;
	preorder(hwq);
	cout << endl;
	system("pause");
	return 0;
}

涉及二叉树的算法不少而且有的也很复杂,我自己的水平有限,所以就不为大家一一介绍了。大家有兴趣也可以去我一个毕业学长的网站上去看。

链接:www.subetter.com(挺好的)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值