// 先序2叉树的递归算法.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
#define MaxSize 100
//2叉树数据定义
typedef struct BiTNode
{
int data;
struct BiTNode *leftchild,*rightchild;
}tree,*TreeNode;
//先序遍历递归算法
void PreOrder(TreeNode root)
{
if(root) //2叉树不为空
{
cout<<root->data; //输出根节点的数据
PreOrder(root->leftchild);
PreOrder(root->rightchild);
}
}
//中序遍历递归算法
void InOrder(TreeNode root)
{
if(root)
{
InOrder(root->leftchild);
cout<<root->data;
InOrder(root->rightchild);
}
}
//后序遍历递归算法
void PostOrder(TreeNode root)
{
if(root)
{
PostOrder(root->leftchild);
PostOrder(root->rightchild);
cout<<root->data;
}
}
//创建一个2叉树
void CreateTree(TreeNode root,int NodeNum) /*先序遍历算法创建*/
{
int x;
int i,layer;
layer = log(double(NodeNum)) / log(double(2)) + 1;
cout<<"Input data for Node"<< NodeNum<<" in layer "<<layer<<endl;
cin>>x;
root->data = x;
cout<<"create left child for Node "<<NodeNum<<" in layer "<<layer<<endl;
cin>>i;
if ( i == 0)
{
root->leftchild = NULL;
}
else
{
root->leftchild = (TreeNode)malloc(sizeof(tree));
CreateTree(root->leftchild, 2*NodeNum);
}
cout<<"create right child for Node"<<NodeNum<<"in layer"<<layer<<endl;
cin>>i;
if ( i == 0)
{
root->rightchild = NULL;
}
else
{
root->rightchild = (TreeNode)malloc(sizeof(tree));
CreateTree(root->rightchild, 2*NodeNum + 1);
}
return ;
}
//先序遍历非递归算法
void PreOrderUnrec(TreeNode bt)
{
TreeNode p;
struct St
{
TreeNode pt;
int tag;
}St[MaxSize];
int top = -1;
top++;
St[top].pt = bt;
St[top].tag = 1;
while (top > -1) /*栈不空时循环*/
{
if(St[top].tag == 1) /* 不能直接访问的情况*/
{
p = St[top].pt;
top--;
if (p)
{
top++; //右孩子进栈
St[top].pt = p->rightchild;
St[top].tag = 1;
top++; //左孩子进栈
St[top].pt = p->leftchild;
St[top].tag = 1;
top++; //根节点进栈
St[top].pt = p;
St[top].tag = 0;
}
}
if(St[top].tag == 0)
{
cout<<St[top].pt->data;
top--;
}
}
}
//中序遍历非递归算法
void InOrderUnrec(TreeNode bt)
{
TreeNode St[MaxSize],p;
int top = -1;
if(bt)
{
p = bt;
while (top > -1 || p)
{
while(p)
{
top++;
St[top] = p;
p = p->leftchild;
}
if(top > -1)
{
p = St[top];
top--;
cout<<p->data;
p = p->rightchild;
}
}
cout<<endl;
}
}
//后序遍历的非递归算法
void PostOrderUnrec(TreeNode bt)
{
TreeNode St[MaxSize],p;
int flag,top = -1;
if (bt)
{
do
{
while(bt)
{
top++;
St[top] = bt;
bt = bt->leftchild;
}
p = NULL;
flag = 1;
while (top != -1&&flag)
{
bt = St[top]; //取出当前的栈顶元素
if (bt->rightchild == p) //右子树不存在或已被访问
{
cout<<bt->data;
top--;
p = bt; //p指向刚被访问的节点
}
else
{
bt = bt->rightchild;
flag = 0; //设置未被访问的标记
}
}
}while (top != -1);
cout<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode r = (TreeNode)malloc(sizeof(tree));
CreateTree(r,1);
cout<<"2叉树先序遍历:"<<endl;
PreOrder(r);
cout<<endl<<"中序遍历:"<<endl;
InOrder(r);
cout<<endl<<"后序遍历:"<<endl;
PostOrder(r);
cout<<endl<<"2叉树先序遍历非递归:"<<endl;
PreOrderUnrec(r);
cout<<endl<<"中序遍历非递归:"<<endl;
InOrderUnrec(r);
cout<<endl<<"后序遍历非递归:"<<endl;
PostOrderUnrec(r);
return 0;
}