您的位置:首页 > 理论基础 > 数据结构算法

数据结构之二叉树的非递归遍历

2013-03-23 13:53 519 查看
// Tree.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "iostream"
#include "stack"

using namespace std;

typedef struct node
{
int data;
struct node *lchild;
struct node *rchild;
}BiTNode, *BiTree;

int CreateBiTree(BiTree &T);
int CreateBiTree(BiTree &T,int &index);
void PreOrder(BiTree root);
void InOrder(BiTree root);
void PostOrder(BiTree root);
int InOrderTraverse(BiTree root);
int InOrderTraverse2(BiTree root);

int element[]={3,7,3,2,1,0,0,7,0,0,0,8,0,10,0,0,17,18,0,0,19,0,27,0,0};
static int index=0;
stack<BiTree> S; // 用于存放待访问结点
int _tmain(int argc, _TCHAR* argv[])
{

BiTree tree;
// 递归的创建二叉树
CreateBiTree(tree,index);
printf("创建二叉树完毕\n");
printf("先序遍历\n");
PreOrder(tree);
printf("\n");
printf("中序遍历二叉树\n");
InOrder(tree);
printf("\n");
printf("二叉树的后序遍历\n");
PostOrder(tree);
printf("\n");
printf("二叉树的非递归中序遍历\n");
InOrderTraverse(tree);
printf("\n");
printf("二叉树的非递归中序遍历,方式2\n");
InOrderTraverse2(tree);
printf("\n");

system("pause");
return 0;
}

// 按照先序顺序,递归的创建二叉树
int CreateBiTree(BiTree &T)
{
int data;
scanf("%d",&data);
if (data==0) // 0代表子节点为空
{
T=NULL;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if (!T)
{
return -1;
}
else
{
T->data=data;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
return 1;
}

// 按照先序顺序,递归的创建二叉树,通过数组输入二叉树中的数据
int CreateBiTree(BiTree &T,int &index)
{
int data=element[index];
if (data==0) // 0代表子节点为空
{
T=NULL;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if (!T)
{
return -1;
}
else
{
T->data=data;
CreateBiTree(T->lchild,++index);
CreateBiTree(T->rchild,++index);
}
}
return 1;
}

// 先序遍历二叉树
void PreOrder(BiTree root)
{
if (root!=NULL)
{
printf("%3d",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}

// 中序遍历
void InOrder(BiTree root)
{
if (root!=NULL)
{
InOrder(root->lchild);
printf("%3d",root->data);
InOrder(root->rchild);
}
}

// 后序遍历
void PostOrder(BiTree root)
{
if (root!=NULL)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%3d",root->data);
}
}

// 非递归的遍历二叉树,中序遍历,方式1
int InOrderTraverse(BiTree root)
{
S.push(root);
BiTree p;
while(!S.empty())
{
while((p=S.top())&&p) // 当栈顶不为空指针时
{
S.push(p->lchild); // 向左走到尽头,最后肯定有个空指针入栈
}
S.pop(); // 空指针出栈
if (!S.empty())
{
p=S.top();
S.pop();// 将上一个待访问的结点出栈
printf("%3d",p->data);  // 访问结点
S.push(p->rchild); // 将右子树进展,用以访问当前结点的右子树
}
}
return 1;
}

// 非递归遍历二叉树,中序遍历,方式2
int InOrderTraverse2(BiTree root)
{
stack<BiTree> S;
BiTree p=root;
// 在这种遍历方式中,空指针不入栈,当遇到空指针则说明需要出栈,访问上一个元素
while(p||!S.empty())
{
if (p) // 指针不为空
{
S.push(p); // 将当前非空结点入栈,向左一直走到尽头
p=p->lchild;
}
else
{
// 如果结点为空,则表示到达叶子结点的下个空节点
p=S.top();
S.pop(); // 获取栈顶指针,并且进行出栈,对栈顶元素进行访问
printf("%3d",p->data);
p=p->rchild; // 对当前结点的右子树进行访问,当前结点的右子树还没有访问过
}
}
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: