⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 二叉树非递归前序.c

📁 本数据结构学习包
💻 C
字号:
#include<stdio.h>
#include<stdlib.h>
typedef char datatype;
typedef struct node            /*二叉树结点定义*/
 {
  datatype data;
  struct node *lchild,*rchild;
  }bintnode;
typedef bintnode *bintree;
typedef struct stack         /*栈结构定义*/
     { bintree data[100];
       int tag[100];          /*为栈中每个元素设置的标记,用于后序遍历*/
       int top;              /*栈顶指针*/
     } seqstack;
/****************************************/
 void push(seqstack *s,bintree t)  /*进栈*/
  { s->data[++s->top]=t;
  }
/*****************************************/
 bintree pop(seqstack *s)  /*出栈*/
 { if (s->top!=-1)
      {s->top--;
      return(s->data[s->top+1]);}
      else
      return NULL;
 }
/******************************************/
void createbintree(bintree *t)       
{/*按照前序遍历的顺序建立一棵给定的二叉树*/ 
 char ch;
 if ((ch=getchar())==' ')
      *t=NULL;
      else {
	  *t=(bintnode *)malloc(sizeof(bintnode));
	  (*t)->data=ch;
	  createbintree(&(*t)->lchild);
	  createbintree(&(*t)->rchild);
      }
 }
/*****************************************/
void preorder1(bintree t)  /*非递归实现二叉树的前序遍历*/
   { seqstack s;
     s.top=-1;
     while ((t) || (s.top!=-1))  /*当前处理的子树不为空或栈不为空则循环*/
      {  while (t)
	      { printf("%c ",t->data);
	        s.top++;
	        s.data[s.top]=t;
	        t=t->lchild;
	      }
	    if (s.top>-1)
	      { t=pop(&s);
	        t=t->rchild;
	      }
      }
    }

main()     /*主程序*/
  { bintree root;
    printf("\n");
    createbintree(&root);
    printf("\n");
    printf("\n前序遍历结果是: ");
    preorder1(root);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -