// 9_17_main.cpp : 二叉树的非递归先序遍历
//
#include "stdafx.h"
#include <conio.h>
#include <stdlib.h>
//数据结构定义及全局常量定义
int const MAXSIZE = 50;
typedef char datatype;
struct node
{
datatype data;
struct node *lchild,*rchild;
};
typedef node bitree;
//建立二叉树函数,返回指向根节点的指针
bitree *CreatTree()
{
//变量定义及初始化
char ch;
bitree *Q[MAXSIZE];
int front,rear;
bitree *root,*currentnode;
root = NULL;
front = 1; rear = 0;
//二叉树的构造过程
printf("请输入根节点字符:(‘#’结束,‘@’为虚节点)/t");
ch = getche();
while (ch != '#')
{
currentnode = NULL;
if (ch != '@')
{
currentnode = (node *)malloc(sizeof(node));
if (currentnode == NULL)
{
printf("分配内存时出错!");
return NULL;
}
else
{
currentnode->data = ch;
currentnode->lchild = NULL;
currentnode->rchild = NULL;
}
}
rear++;
Q[rear] = currentnode;
if (rear == 1)
{
root = currentnode;
}
else
{
if (currentnode && Q[front])
{
if (rear%2 == 0)
{
Q[front]->lchild = currentnode;
}
else
Q[front]->rchild = currentnode;
}
//下面有可能出错
if (rear%2 == 1)
{
front++;
}
}
printf("/n请输入节点字符:(‘#’结束,‘@’为虚节点)/t");
ch = getche();
}
return root;
}
//递归的先序遍历二叉树程序
void PreOrder_Recursion(bitree *root)
{
if (root != NULL)
{
{
printf("%c/t",root->data);
PreOrder_Recursion(root->lchild);
PreOrder_Recursion(root->rchild);
}
}
return;
}
//非递归的先序遍历二叉树程序
void PreOrder(bitree *root)
{
bitree *stack[MAXSIZE]; //用栈来模拟递归函数的调用
int top; //指向栈顶
bitree *tnode;
if (root != NULL)
{
top = -1;
tnode = root;
while ((top != -1) || (tnode != NULL))
{
while (tnode != NULL)
{
if (top == MAXSIZE-1)
{
printf("栈溢出……");
return;
}
else
{
printf("%c/t",tnode->data);
top++;
stack[top] = tnode;
tnode = tnode->lchild;
}
}
tnode = stack[top];
top--;
tnode = tnode->rchild;
}
return;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
bitree *root;
root = CreatTree();
if (root != NULL)
{
printf("/n以下显示的是递归调用的二叉树遍历:/n");
PreOrder_Recursion(root);
printf("/n以下显示的是非递归调用的二叉树遍历:/n");
PreOrder(root);
}
printf("/n请按任意键继续……");
getche();
return 0;
}