#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode
{
char data;
struct TreeNode* lchild;
struct TreeNode* rchild;
int flag;//非递归后序遍历
}TreeNode;
typedef struct StackNode
{
TreeNode* data;
struct Stack* next;
}StackNode;
StackNode* StackInit(TreeNode* T)//利用栈对树进行遍历
{
StackNode* S = (StackNode*)malloc(sizeof(StackNode));
S->data = NULL;
S->next = NULL;
return S;
}
void createTree(TreeNode** T,char* data,int* index)
{
char ch;
ch = data[*index];
*index += 1;
if (ch == NULL)
{
*T = NULL;
}
else
{
*T = (TreeNode*)malloc(sizeof(TreeNode));
(*T)->data = ch;
(*T)->flag = 0;
createTree((*T)->lchild, data, index);
createTree((*T)->rchild, data, index);
}
}
void Push(TreeNode* data, StackNode* S)//入栈
{
StackNode* node = (StackNode*)malloc(sizeof(StackNode));
node->data = data;
node->next = S->next;
S->next = node;
}
int isEmpty(StackNode* S)
{
if (S->next == NULL)
{
return 1;
}
else
{
return 0;
}
}
StackNode* popStack(StackNode* S)//出栈
{
if (isEmpty(S))
{
return NULL;
}
else
{
StackNode* node = S->next;
S->next = node->next;
return node;
}
}
StackNode* gettopStack(StackNode* S)//栈顶元素
{
if (isEmpty(S))
{
return NULL;
}
else
{
StackNode* node = S->next;
return node;
}
}
void preOrder(TreeNode* T)//先序遍历(非递归)
{
TreeNode* node = T;
StackNode* S = StackInit(S);
while (node || !isEmpty(S))
{
if (node)
{
printf("%c ",node->data);
Push(node,S);
node = node->lchild;
}
else
{
node = popStack(S)->data;
node = node->rchild;
}
}
}
void inOrder(TreeNode* T)//中序遍历(非递归)
{
TreeNode* node = T;
StackNode* S = StackInit(S);
while (node || !isEmpty(S))
{
if (node)
{
Push(node, S);
node = node->lchild;
}
else
{
node = popStack(S)->data;
printf("%c ", node->data);
node = node->rchild;
}
}
}
//后序遍历:从根节点开始寻找最左边的节点,
//依次入栈,出栈前,判断其是否有右子树,
//并且未被访问,则将其有子树入栈。
void postOrder(TreeNode* T)
{
TreeNode* node = T;
StackNode* S = StackInit(S);
while (node || !isEmpty(S))
{
if (node)
{
Push(node, S);
node = node->lchild;
}
else
{
TreeNode* top = gettopStack(S)->data;
if (top->rchild && top->rchild->flag == 0)
{
top=top->rchild;
Push(top, S);
node = top->lchild;
}
else
{
top = popStack(S)->data;
printf("%c ",top->data);
top->flag = 1;
}
}
}
}
int main(int argc,char* argv[])
{
TreeNode* T;
int index = 0;
createTree(&T, argv[1], &index);
preOrder(T);
printf("\n");
inOrder(T);
printf("\n");
postOrder(T);
printf("\n");
return 0;
}
C语言实现二叉树的遍历(非递归)
最新推荐文章于 2023-03-14 16:08:04 发布