图1 二叉树
#include <iostream.h>
#include <stack>
#include <ctime>
#include <assert.h>
#include <malloc.h>
#define MaxSize 20
#define Base 100
#define NULLKEY '?'
using namespace std;
typedef char ElemType;
typedef struct treeT
{
ElemType data;//二叉树节点存储的元素的值
struct treeT *left;//左孩子;
struct treeT *right;//右孩子;
}treeT,*PTreeT;
//输出节点元素的值;
void visist(PTreeT root)
{
if (root!=NULL)
{
cout<<root->data<<"\t";
}
}
// 先序创建一颗二叉树
PTreeT createTree(PTreeT &root)
{
char ch;
scanf("%c",&ch);
if (ch==NULLKEY)
{
root=NULL;
return root;
}
else
{
root=(PTreeT)malloc(sizeof(treeT));
root->data=ch;
createTree(root->left);
createTree(root->right);
return root;
}
}
//二叉树的先序遍历,先采用递归的方式进行调用;
void preOrder(PTreeT root)
{
if (root!=NULL)
{
visist(root);
preOrder(root->left);
preOrder(root->right);
}
}
void preOrderRecursive(PTreeT root)//先序遍历非递归调用;
{
stack<treeT *> s;
while ((NULL != root) || !s.empty())
{
if (NULL != root)
{
s.push(root);
root = root->left;
}
else
{
root = s.top();
visist(root);
s.pop();
root = root->right;
}
}
}
//先序遍历版本
void preOrderRecursiveByZJ(PTreeT root)
{
PTreeT stack[MaxSize+1],p;
int top=1;
if (root!=NULL)
{
stack[top]=root;
while (top>0)
{
p=stack[top--];
cout<<p->data<<"\t";
if (p->right!=NULL)
{
stack[++top]=p->right;
}
if (p->left!=NULL)
{
stack[++top]=p->left;
}
}
}
}
//中序遍历,递归版本
void inOrder(PTreeT root)
{
if (root!=NULL)
{
inOrder(root->left);
cout<<root->data<<"\t";
inOrder(root->right);
}
}
//中序遍历,非递归版本
void inOrderRecursive(PTreeT root)
{
PTreeT stack[MaxSize+10];
PTreeT p=root;
int top=0;
while (p!=NULL||top>0)
{
if (p!=NULL)
{
stack[++top]=p;
p=p->left;
}
else
{
p=stack[top--];
cout<<p->data<<"\t";
p=p->right;
}
}
}
//二叉树的后序递归以及非递归算法
void postOrder(PTreeT root)
{
if (root!=NULL)
{
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<"\t";
}
}
void postOrderRecursive(PTreeT root)
{
if (!root) return;
stack<PTreeT> s1,s2;//建立两个工作栈;
PTreeT p=NULL;//工作指针
s1.push(root);//将根节点压入栈s1中;
while (!s1.empty())
{
p=s1.top(); //将p指向s1中的栈顶元素;
s1.pop(); //将保存在栈s1中的根节点出栈;
s2.push(p); //将s1中的栈顶元素压入栈s2中;
if (p->left) //判断当前节点p的左子树是否为空,不为空则压入栈s1;
{
s1.push(p->left);
}
if (p->right)//判断当前节点p的右子树是否为空,不为空则压入栈s1;
{
s1.push(p->right);
}
}
while (!s2.empty())//所有的节点在上面的循环完成之后都已经压入栈s2中,现在只需要输出栈s2中的元素,就是后序遍历;
{
cout<<s2.top()->data<<"\t";
s2.pop();
}
cout<<endl;
}
void main()
{
PTreeT root=NULL;
printf("请通过先序创建二叉树,输入二叉树节点:");
createTree(root);
cout<<"二叉树的先序递归遍历:"<<endl;
preOrder(root);
cout<<endl;
cout<<endl;
cout<<"二叉树的先序非递归遍历:"<<endl;
preOrderRecursiveByZJ(root);
cout<<endl;
cout<<"二叉树的中序递归遍历:"<<endl;
inOrder(root);
cout<<endl;
cout<<"二叉树的中序非递归遍历:"<<endl;
inOrderRecursive(root);
cout<<endl;
cout<<"二叉树的后序递归遍历:"<<endl;
postOrder(root);
cout<<endl;
cout<<"二叉树的后序非递归遍历:"<<endl;
postOrderRecursive(root);
cout<<endl;
}
运行结果: