#include <stdio.h>
#include <stdlib.h>
struct treeNode {
char data;
struct treeNode* LChild;
struct treeNode* RChild;
};
struct treeNode* createNode(char data)
{
struct treeNode* newNode = (struct treeNode *)malloc(sizeof(struct treeNode));
newNode->data = data;
newNode->LChild = NULL;
newNode->RChild = NULL;
return newNode;
}
void linkNode(struct treeNode* currentNode, struct treeNode* LChildNode, struct treeNode* RChildNode)
{
currentNode->LChild = LChildNode;
currentNode->RChild = RChildNode;
}
void printNode(struct treeNode* currentNode)
{
printf("%c ", currentNode->data);
}
void PreOrder(struct treeNode* root)
{
if(root == NULL)
return;
struct treeNode* stack[10];
int stackTop = -1;
struct treeNode* t = root;
while(stackTop != -1 || t)
{
while(t)
{
printf("%c ", t->data);
stack[++stackTop] = t;
t = t->LChild;
}
if(stackTop != -1)
{
t = stack[stackTop--];
t = t->RChild;
}
}
}
void InOrder(struct treeNode* root)
{
if(root == NULL)
return;
struct treeNode* stack[10];
int stackTop = -1;
struct treeNode* t = root;
while(stackTop != -1 || t)
{
while(t)// 走到树最左边的底部结点
{
stack[++stackTop] = t;
t = t->LChild;
}
if(stackTop != -1)
{
t = stack[stackTop--];
printf("%c ", t->data);
t = t->RChild;
}
}
}
void PostOrder(struct treeNode* root)
{
if(root == NULL)
return;
struct treeNode* stack[10];
int stackTop = -1;
struct treeNode* t = root;
struct treeNode* temp;
while(stackTop != -1 || t)
{
while(t)
{
stack[++stackTop] = t;
t = t->LChild;
}
t = stack[stackTop];
if(t->RChild == NULL || t->RChild == temp)
{
printf("%c ", t->data);
stackTop--;
temp = t;
t = NULL;
}
else
{
t = t->RChild;
}
}
}
int main()
{
struct treeNode* A = createNode('A');
struct treeNode* B = createNode('B');
struct treeNode* C = createNode('C');
struct treeNode* D = createNode('D');
struct treeNode* E = createNode('E');
struct treeNode* F = createNode('F');
struct treeNode* G = createNode('G');
struct treeNode* H = createNode('H');
linkNode(A, B, C);
linkNode(B, D, E);
linkNode(C, F, G);
linkNode(F, NULL, H);
PreOrder(A);
printf("\n");
InOrder(A);
printf("\n");
PostOrder(A);
printf("\n");
return 0;
}
二叉树前中后序非递归遍历C语言实现
最新推荐文章于 2020-07-23 16:17:55 发布