二叉树的遍历

所谓二叉树的遍历无非是三种,先序遍历,中序遍历,后序遍历,而此间的先中后指明的都是根的所在,其他都是先左子树,而后右子树

也即先序遍历:根  左子树  右子树

中序遍历:左子树 根   右子树

后序遍历:左子树  右子树  根

#include<iostream>
using namespace std;
struct node{
	node(){
		value = -1;
		left = NULL;
		right = NULL;
	}
	int value;
	node* left;
	node* right;
};
static node* head = NULL;
void insert_node(int value)
{
	if (value == -1)
	{
		return;
	}
	
	if (NULL == head)
	{
		head = new node();
		head->value = value;
	}
	else
	{
		node* tmp = head;
		while (tmp != NULL)
		{
			if (tmp->value > value)
			{
				//value应该在tmp的右子树上
				if (NULL == tmp->right)
				{
					tmp->right = new node();
					tmp->right->value = value;
					break;
				}
				else
				{
					tmp = tmp->right;
				}
			}
			else
			{
				if (NULL == tmp->left)
				{
					tmp->left = new node();
					tmp->left->value = value;
					break;
				}
				else
				{
					tmp = tmp->left;
				}
			}
		}
	}
}
void pre_itera(node* mm)
{
	if (NULL == mm)
	{
		return;
	}
	
	cout << mm->value << endl;
	pre_itera(mm->left);
	pre_itera(mm->right);
}
void getMax_Min(node*mm,int& max,int& min)
{
	if (NULL != mm)
	{
		if (mm->value > max)
		{
			max = mm->value;
		}
		if (mm->value < min)
		{
			min = mm->value;
		}
		getMax_Min(mm->left, max, min);
		getMax_Min(mm->right, max, min);
	}
}
void mid_itera(node* mm)
{
	if (NULL!= mm)
	{
		mid_itera(mm->left);
		cout << mm->value << endl;
		mid_itera(mm->right);
	}
	
}
void aft_itera(node* mm)
{
	if (NULL == mm)
	{
		return;
	}
	aft_itera(mm->left);
	
	aft_itera(mm->right);
	cout << mm->value << endl;
}
int main()
{
	
	
	int a[6] = { 10, 12, 5, 13, 11, 6 };
	int i = 0;
	while (i!=6)
	{
		insert_node(a[i++]);
	}
	cout << "先序遍历结果:\n";
	pre_itera(head);
	cout << "中序遍历结果:\n";
	mid_itera(head);
	cout << "后序遍历结果:\n";
	aft_itera(head);
	cout << "获得树中最大值和最小值:\n";
	int max=a[0], min=a[0];
	getMax_Min(head, max, min);
	cout << "最大值是:"<<max<<endl;
	cout << "最小值是:" << min;
}
而对于最大最小值的获取无非是进行整个二叉树的遍历,将最大值,最小值设置为数组中的第一个元素即可,便利过程中一次比较,记录下最大最小值即可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值