如何实现二叉树的非递归先序遍历

//头文件

#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
typedef char TElemType;
typedef struct Node
{
 TElemType data;
 struct Node *Lchild,*Rchild;
}BiTreeNode,*BiTree;
#define STACKINCREAMENT 10
typedef BiTreeNode SElemType;
typedef struct stack
{
 SElemType * base;
 SElemType * tope;
 int stacksize;
}SqStack;
void copy(BiTreeNode *S,BiTreeNode *T)
{
 S->data=T->data;
 S->Lchild=T->Lchild;
 S->Rchild=T->Rchild;
}
void initStack(SqStack *S)
//栈的初始化操作
{
 S->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
 S->tope=S->base;
 S->stacksize=STACK_INIT_SIZE;
}

void Push(SqStack *S,SElemType e)
//向栈内压入元素
{
 if(S->tope-S->base>=S->stacksize)
 {
  S->base=(SElemType *)realloc(S->base,(S->stacksize+STACKINCREAMENT)*sizeof(SElemType));
 
  S->tope=S->base+S->stacksize;
  S->stacksize+=STACKINCREAMENT;
 } 
 copy(S->tope,&e);
 S->tope++;
}

 

SElemType Pop(SqStack *S)
//删除栈顶元素
{
 SElemType e;
 if(S->tope==S->base)
  exit(0);
 S->tope--;
 copy(&e,S->tope);
 return e;
}

int stackEmpty(SqStack *S)
{
 if(S->tope==S->base)
  return 1;
 else return 0;
}

 

//CPP文件

#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include "stack.h"
int count;
BiTreeNode *bt;
BiTreeNode *s[20];
SqStack S;
BiTreeNode *Creat_Bt()
//二叉树的构造。
{
 int i,j;
 TElemType x;
 BiTreeNode *p;
 BiTreeNode *root=(BiTreeNode *)malloc(sizeof(BiTreeNode));
 printf("  i, x/n");
 scanf("%d,%c",&i,&x);
 while(i!=0&&x!='#')
 {
  p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
  p->data=x;
  p->Lchild=NULL;
  p->Rchild=NULL;
  s[i]=p;
  if(i==1)
   bt=p;
  else
  {
   j=i/2;
   if(i%2==0)
    s[j]->Lchild=p;
   else
    s[j]->Rchild=p;
  }
  printf("  i, x/n");
  scanf("%d,%c",&i,&x);
 }
 return bt;
}
BiTreeNode * LTraverse(BiTreeNode *bt)
{
 BiTreeNode *temp=bt;
 printf("%c",temp->data);
 while(temp->Lchild!=NULL)
 {
  printf("%c",temp->Lchild->data);
  if(temp->Rchild!=NULL)
  {
   Push(&S,*temp->Rchild);
  }
  temp=temp->Lchild;
 }
 return temp;
}

void Traverse (BiTreeNode *bt)
//非递归先序遍历二叉树

 BiTreeNode *temp=bt;
 temp=LTraverse(temp);
 while(stackEmpty(&S)==0)
 {
  if(temp->Lchild==NULL)
  {
   *temp=Pop(&S);
  }
  temp=LTraverse(temp);
 }
 
}
void main()
{
 BiTreeNode *bt;
 bt=Creat_Bt();
 putchar('/n');
 Traverse(bt);
 getch();
}

 

输入样例

1,I

2,

3,s

4,l

5,e

6,d

7,n

8,o

9,v

10,

11,c

12,#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值