二叉树前序遍历和中序遍历 非递归算法
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct BSTreeNode
{
int value;
struct BSTreeNode *left;
struct BSTreeNode *right;
};
struct stack
{
struct BSTreeNode *elements[MAX];
int top;
};
struct BSTreeNode *root;
struct stack s;
void init()
{
s.top = 0;
}
void push(struct BSTreeNode *temp)
{
s.elements[s.top++] = temp;
}
struct BSTreeNode *pop()
{
return s.elements[--s.top];
}
int isEmpty()
{
return s.top == 0;
}
void create(struct BSTreeNode **t)
{
char temp;
struct BSTreeNode *p;
scanf("%c",&temp);
if(temp == '.')
*t = NULL;
else
{
p = (struct BSTreeNode *)malloc(sizeof(struct BSTreeNode));
p->value = temp;
*t = p;
create(&(p->left));
create(&(p->right));
}
}
void preorder(struct BSTreeNode *t)
{
struct BSTreeNode *temp = t;
while(temp != NULL || s.top != 0)
{
while(temp != NULL)
{
printf("%c",temp->value);
push(temp);
temp = temp->left;
}
if(s.top != 0)
{
temp = pop();
temp = temp->right;
}
}
printf("\n");
}
void inorder(struct BSTreeNode *t)
{
struct BSTreeNode *temp = t;
while(temp != NULL || s.top != 0)
{
while(temp != NULL)
{
push(temp);
temp = temp->left;
}
if(s.top != 0)
{
temp = pop();
printf("%c",temp->value);
temp = temp->right;
}
}
printf("\n");
}
int main()
{
struct BSTreeNode *root;
init();
create(&root); //ABD.G...CE..F...
preorder(root);//ABDGCEF
inorder(root);//DGBAECF
return 0;
}