c++, 二叉树的非递归遍历

#include<iostream>
#include<stack>  // 引入标准模板库stack头文件
using namespace std;

struct Tree
{
	char data;
	Tree* Lson;
	Tree* Rson;
};
Tree* T;

// 输入一个二叉树
void creatTree(Tree* &tree)
{
	char ch;
	if ((ch = getchar()) == '#')
	{
		tree = NULL;
	}
	else
	{
		tree = new Tree;
		tree->data = ch;
		creatTree(tree->Lson);
		creatTree(tree->Rson);
	}
}

// 非递归前序遍历
void PreOrder_Nor1(Tree* tree)
{

	if (tree == NULL)
		return;
	stack<Tree*>s;  //创建一个空栈
	while (tree != NULL || !s.empty())
	{
		while (tree != NULL)
		{
			cout << tree->data << " ";
			s.push(tree);
			tree = tree->Lson;
		}
		if (!s.empty())
		{
			tree = s.top();	
			tree = tree->Rson;
			s.pop();
		}
	}
}

// 非递归中序遍历
void InOrder_Nor1(Tree* tree)
{
	if (tree == NULL)
		return;
	stack<Tree*>s; //创建一个空栈
	while (tree != NULL || !s.empty())
	{
		if (tree->Lson)
		{
			s.push(tree);
			tree = tree->Lson;
		}
		else
		{
			cout << tree->data << " ";
			tree = tree->Rson;
			while (!tree && !s.empty())
			{
				tree = s.top();
				cout << tree->data << " ";	
				s.pop();
				tree = tree->Rson;
			}
		}
	}
}

//非递归后序遍历
void PosOrder(Tree* tree)
{
	if (tree == NULL)
		return;
	stack<Tree*>s; //创建一个空栈
	Tree* pPre = NULL;
	s.push(tree);
	while (!s.empty())
	{
		tree = s.top();
		if ((tree->Rson == NULL && tree->Rson == NULL) ||
			(pPre != NULL && (tree->Lson == pPre || tree->Rson == pPre)))
		{
			cout << tree->data << " ";
			pPre = tree;
			s.pop();
		}
		else
		{
			if (tree->Rson != NULL)
				s.push(tree->Rson);
			if (tree->Lson != NULL)
				s.push(tree->Lson);
		}
	}
}

int main()
{
	cout << "输入一个二叉树(按照这个二叉树的前序遍历输入,若子节点为空就输入 #  ):" << endl;
	creatTree(T);

	cout << "前序遍历:";
	PreOrder_Nor1(T);
	cout << endl;

	cout << "中序遍历:";
	InOrder_Nor1(T);
	cout << endl;

	cout << "后序遍历:";
	PosOrder(T);
	cout << endl;

	delete T;
	return 0;
}
//==感悟:栈内存放的是节点,push和pop的都是节点,tree != NULL是节点不为空   //
//        tree->date是节点上的数字,所以不存在tree->data == NULL这种形式  //
//     	  tree->Lson,tree->Rson是节点的左右儿子节点,不是这个节点的数字   //

如图:

输出结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值