#include<stdio.h>
#include<stdlib.h>
//树结点创建
typedef char E;//树结点存的数据类型
typedef struct TreeNode* Node;//树结点指针
struct TreeNode{
E element;//树结点存的数据
struct TreeNode* left;//树结点左子结点
struct TreeNode* right;//树结点右子结点
};
//栈结点创建
typedef struct StackNode *SNode;//栈结点
struct StackNode
{
Node element;//用栈存放树结点
struct StackNode* next;//栈结点下一个
};
//栈函数区
//创建一个新的栈
void initStack(SNode head)
{
head->next = NULL;
}
//判断栈是否为空
int isEmpty(SNode head)
{
if(head->next==NULL)
{
return 0;
}
else
{
return 1;
}
}
//入栈
int pullStack(SNode head,Node element)
{
SNode node = malloc(sizeof(struct StackNode));
if(node==NULL)
{
return 0;
}
node->element=element;
node->next=head->next;
head->next=node;
return 1;
}
//出栈
Node popStack(SNode head)
{
SNode top = head->next;
head->next = head->next->next;
Node e = top->element;
free(top);
return e;
}
//二叉树遍历区
//前序遍历
//变量根结点
void preOrder(Node root)
{
struct StackNode stack;//创建一个栈
initStack(&stack);//初始化栈
while(root!=NULL||isEmpty(&stack))//根结点为空并且栈清零结束
{
while(root)//根结点如果为空结束,此时栈为为空结点的父结点
{
pullStack(&stack,root);//当前结点入栈
printf("%c",root->element);
root=root->left;//往左找左子节点
}
root=popStack(&stack);//找到最后入栈的结点
root=root->right;//看有无右结点
}
}
//二叉树遍历区
//中序遍历
//变量根结点
void inOrder(Node root)
{
struct StackNode stack;//创建一个栈
initStack(&stack);//初始化栈
while(root!=NULL||isEmpty(&stack))//根结点为空并且栈清零结束
{
//找到最左边的没有子结点的结点
while(root)//根结点如果为空结束,此时栈为为空结点的父结点
{
pullStack(&stack,root);//当前结点入栈
root=root->left;//往左找左子节点
}
root=popStack(&stack);//找到最后入栈的结点
printf("%c",root->element);//打印
root=root->right;//看有无右结点
}
}
int main()
{
Node a = malloc(sizeof(struct TreeNode));
Node b = malloc(sizeof(struct TreeNode));
Node c = malloc(sizeof(struct TreeNode));
Node d = malloc(sizeof(struct TreeNode));
Node e = malloc(sizeof(struct TreeNode));
Node f = malloc(sizeof(struct TreeNode));
a->element='A';
b->element='B';
c->element='C';
d->element='D';
e->element='E';
f->element='F';
a->left=b;
a->right=c;
b->left=d;
b->right=e;
c->left=NULL;
c->right=f;
d->left=NULL;
d->right=NULL;
e->left=NULL;
e->right=NULL;
f->left=NULL;
f->right=NULL;
preOrder(a);
printf("\n");
inOrder(a);
printf("\n");
return 0;
}
数据结构笔记(十五)二叉树的遍历(循环)
于 2024-03-18 22:37:00 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)