结构体
typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
利用栈实现前序遍历
void preordernoRecusion(BTNode *bt) //栈实现前序遍历
{
if(bt!=NULL)
{
BTNode *Stack[maxSize];
int top=-1;
BTNode *p;
Stack[++top]=bt;
while(top!=-1)
{
p=Stack[top--];
printf("%c ",p->data);
if(p->rchild!=NULL)
Stack[++top]=p->rchild;
if(p->lchild!=NULL)
Stack[++top]=p->lchild;
}
}
}
利用栈实现中序遍历
void inordernoRecursion(BTNode *bt) //栈实现中序遍历
{
if(bt!=NULL)
{
BTNode *Stack[maxSize];
int top=-1;
BTNode *p;
p=bt;
while(top!=-1||p!=NULL)
{
while(p!=NULL)
{
Stack[++top]=p;
p=p->lchild;
}
if(top!=-1)
{
p=Stack[top--];
printf("%c ",p->data);
p=p->rchild;
}
}
}
}
双栈后序遍历
void postordernoRecursion(BTNode *bt) //双栈实现后序遍历
{
if(bt!=NULL)
{
BTNode *stack1[maxSize];int top1=-1;
BTNode *stack2[maxSize];int top2=-1;
BTNode *p;
stack1[++top1]=bt;
while(top1!=-1)
{
p=stack1[top1--];
stack2[++top2]=p;
if(p->lchild!=NULL)
stack1[++top1]=p->lchild;
if(p->rchild!=NULL)
stack1[++top1]=p->rchild;
}
while(top2!=-1)
{
p=stack2[top2--];
printf("%c ",p->data);
}
}
}
队列实现层次遍历
void level(BTNode *p) //层次遍历
{
BTNode *que[maxSize];
int front,rear;
front=rear=0;
BTNode *q;
if(p!=NULL)
{
rear=(rear+1)%maxSize;
que[rear]=p;
while(front!=rear)
{
front=(front+1)%maxSize;
q=que[front];
printf("%c ",q->data);
if(q->lchild!=NULL)
{
rear=(rear+1)%maxSize;
que[rear]=q->lchild;
}
if(q->rchild!=NULL)
{
rear=(rear+1)%maxSize;
que[rear]=q->rchild;
}
}
}
}
递归方式
https://blog.csdn.net/qq_44976531/article/details/108221025