二叉树非递归遍历

#include
#include
#include
#include
#include 
#include
#include 
using namespace std;
typedef struct BinaryTree
{
	char val;
	struct  BinaryTree *left;
	struct  BinaryTree *right;
}BinaryTree,*BitTree;

//******递归建立二叉树*****// 
//先建立根节点,再建立左子树,最后建立右子树
/***********
测试用例:
         a
    b         c
  #    d    #    e
     f   #     #   #
   #   #
输入:ab#df###c#e##  
***************/
int create_tree(BitTree &T)
{
	char val = getchar();
	if(val == '#')
	T = NULL;
	else  
	{
		T = new BinaryTree;
		T -> val = val;
		create_tree(T->left);
		create_tree(T->right);
	}
	return 0;
}
//二叉树先序非递归遍历 
int Preorder(BitTree T) 
{
	stack sta;
	BitTree  p = T;
	while(p || !sta.empty())
	{
		if(p)
		{
			//输出根节点,根节点入栈,遍历左子树
			cout<val<<" ";
			sta.push(p);
			p = p->left; 
		}
		else
		{
			//记录根节点,然后根节点出栈,遍历右子树 
			p = sta.top();
			sta.pop();
			p = p->right;
		}
	}
	return 0;	
}
//二叉树中序非递归遍历
int Midorder(BitTree T) 
{
	stack sta;
	BitTree  p = T;
	while(p || !sta.empty())
	{
		if(p)
		{
			//此时不输出根节点,根节点入栈,遍历左子树 
			sta.push(p);
			p = p->left; 
		}
		else //当走到最左端时,弹出栈顶,打印输出该节点,转向右节点 
		{
			p = sta.top();
			sta.pop();
			cout<val<<" "; 
			p = p->right;
		}
	}
	return 0;	
}
//二叉树后序非递归遍历
int Postorder(BitTree T)
{
	stack sta;
	//bool flag = false;
	BitTree pLastvisit,p; //pLastvisit标记上次访问的节点 
	pLastvisit = NULL;    //p标记当前访问节点 
	p = T;
	while(p) //寻找整棵树最左边的节点 
	{
		sta.push(p);
		p=p->left;
	}
	while(!sta.empty())
	{ 
		p = sta.top();
		sta.pop();
		//根节点被访问的前提是:无右子树或者右子树被访问过
		if(p->right==NULL|| p->right==pLastvisit)
		{
			cout<val<<" ";
			//修改上次被访问的节点 
			pLastvisit = p;
		} 
		else  //否则根节点现在不能访问 
		{
			sta.push(p);//根节点需要再次入栈 
			p = p->right;
			while(p)   //寻找右子树中最左边的节点 
			{ 
				sta.push(p);
				p = p->left;
			}
		} 
	}	
	return 0;
} 
//*****按层遍历(未分层打印)*****//
int layerorder(BitTree T)
{
	queue q;
	BitTree p = NULL;
	if(T)
	q.push(T);  //根节点入队列 
	while(!q.empty())
	{
		p = q.front();
		q.pop();
		cout<val<<" ";  //打印根节点,左右子节点非空,即入队列 
		if(p->left)
		q.push(p->left);
		if(p->right)
		q.push(p->right);
		
	} 
	cout<

程序运行结果:

二叉树非递归遍历_第1张图片

你可能感兴趣的:(数据结构与算法)