您的位置:首页 > 其它

二叉树的遍历

2015-06-17 20:59 381 查看
所谓二叉树的遍历无非是三种,先序遍历,中序遍历,后序遍历,而此间的先中后指明的都是根的所在,其他都是先左子树,而后右子树

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

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

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

#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;
}
而对于最大最小值的获取无非是进行整个二叉树的遍历,将最大值,最小值设置为数组中的第一个元素即可,便利过程中一次比较,记录下最大最小值即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: