二叉树的遍历(递归与非递归)

二叉树的常见遍历:

//二叉树
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef int ElemType;
struct BinaryTreeNode
{
	ElemType data;
	BinaryTreeNode *left;
	BinaryTreeNode *right;
};

BinaryTreeNode* CreateBinaryTree()  //前序构造二叉树
{
	BinaryTreeNode *root=new BinaryTreeNode;
//	root->left=root->right=NULL;
	ElemType e;
	cin>>e;
	if(e==0)
	root=NULL;
	else
	{
		root->data=e;
		root->left=CreateBinaryTree();
		root->right=CreateBinaryTree();
	}
	return root;
}

void PreOrder(BinaryTreeNode *root)       //前序遍历
{
	if(root)
	{
		cout<<root->data<<" ";
		PreOrder(root->left);
		PreOrder(root->right);
	}
}

void PreOrder2(BinaryTreeNode *root)        //非递归前序遍历
{
	stack<BinaryTreeNode*> s;
	s.push(NULL); //需初始化
	while (root!=NULL)
	{
		cout<<root->data<<" ";
		if(root->right!=NULL) s.push(root->right);
		if(root->left!=NULL)  root=root->left;
		else { root=s.top();s.pop();}
	}
}
void InOrder(BinaryTreeNode *root)  //递归中序遍历
{
	if(root)
	{
		InOrder(root->left);
		cout<<root->data<<" ";
		InOrder(root->right);
	}
}

void InOrder2(BinaryTreeNode *root)  //非递归中序遍历
{
	stack<BinaryTreeNode*> s;
	do 
	{
		while (root!=NULL)
		{
			s.push(root);
			root=root->left;
		}
		if(!s.empty())
		{
			root=s.top(); s.pop(); cout<<root->data<<" ";
			root=root->right;
		}
	} while (root!=NULL||!s.empty());
}

void Level(BinaryTreeNode *root)  //层次遍历
{
	queue<BinaryTreeNode *> q;
	BinaryTreeNode *temp=NULL;
	q.push(root);
	while (!q.empty())
	{
		temp=q.front(); q.pop();
		cout<<temp->data<<" ";
		if(temp->left!=NULL) q.push(temp->left);
		if(temp->right!=NULL) q.push(temp->right);
	}
}
void PostOrder(BinaryTreeNode *root)  //后序遍历
{
	if(root)
	{
		PostOrder(root->left);
		PostOrder(root->right);
		cout<<root->data<<" ";
	}
}
int main()
{
	BinaryTreeNode* root=NULL;
	root=CreateBinaryTree();
	PreOrder(root);
	PreOrder2(root);
	cout<<endl;
	InOrder(root);
	InOrder2(root);
	cout<<endl;
	PostOrder(root);
	cout<<endl;
	Level(root);
	system("pause");
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值