二叉树的常见遍历:
//二叉树
#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;
}