#include<stdio.h> #include<string.h> #include<stdlib.h> #define Size 100 #define Resize 10 typedef struct Bitnode{ //定义结点 char data; struct Bitnode *lchild,*rchild; }Bitnode,*Bitree; typedef struct Stack{ //定义栈 Bitree *base; int top; int stacksize; }Stack; void Initstack(Stack &S) //建栈 { S.base=(Bitree*)malloc(Size*sizeof(Bitnode)); if(!S.base) return; S.top=0; S.stacksize=Size; } void Pushstack(Stack &S,Bitree e) //入栈 { if(S.top==S.stacksize) { S.base=(Bitree*)realloc(S.base,(S.stacksize+Resize)*sizeof(Bitnode)); if(!S.base) return; S.stacksize+=Resize; } S.base[S.top++]=e; } Bitree Pop(Stack &S,Bitree &e) //出栈 { if(S.top==0) return 0; e=S.base[--S.top]; return e; } int Emptystack(Stack &S) //栈的判空操作 { if(S.top==0) return 1; return 0; } Bitree Gettop(Stack &S,Bitree &e) //取栈顶元素 { if(S.top==0) return 0; e=S.base[S.top-1]; return e; } void Createbitree(Bitree &bt) { //建立二叉树的二叉链表 char ch; ch=getchar(); if(ch==‘#‘) bt=NULL; else { bt=(Bitree)malloc(sizeof(Bitnode)); bt->data=ch; bt->lchild=bt->rchild=NULL; Createbitree(bt->lchild); Createbitree(bt->rchild); } } void Pretraverse(Bitree bt) {//递归先序遍历 if(bt) { printf("%c ",bt->data); Pretraverse(bt->lchild); Pretraverse(bt->rchild); } } void Preordertraverse(Bitree bt) {//非递归先序遍历 Stack S; Bitree p; if(bt) { Initstack(S);Pushstack(S,bt); while(!Emptystack(S)) { while(Gettop(S,p)&&p) { printf("%c ",p->data); Pushstack(S,p->lchild); } Pop(S,p); if(!Emptystack(S)) { Pop(S,p); Pushstack(S,p->rchild); } } } } void Intraverse(Bitree bt) {//递归中序遍历 if(bt) { Intraverse(bt->lchild); printf("%c ",bt->data); Intraverse(bt->rchild); } } void Inordertraverse(Bitree bt) {//非递归中序遍历 Stack S; Bitree p; if(bt) { Initstack(S); Pushstack(S,bt); while(!Emptystack(S)) { while(Gettop(S,p)&&p) Pushstack(S,p->lchild); Pop(S,p); if(!Emptystack(S)) { Pop(S,p); printf("%c ",p->data); Pushstack(S,p->rchild); } } } } void Posttraverse(Bitree bt) {//递归后序遍历 if(bt) { Posttraverse(bt->lchild); Posttraverse(bt->rchild); printf("%c ",bt->data); } } void Postordertraverse(Bitree bt) {//非递归后序遍历 Bitree p,q; Stack S; if(bt) { Initstack(S); Pushstack(S,bt); while(!Emptystack(S)) { while(Gettop(S,p)&&p) Pushstack(S,p->lchild); Pop(S,p); if(!Emptystack(S)) { Gettop(S,p); if(p->rchild) Pushstack(S,p->rchild); else { Pop(S,p); printf("%c ",p->data); while(!Emptystack(S)&&Gettop(S,q)&&q->rchild==p) { Pop(S,p); printf("%c ",p->data); } if(!Emptystack(S)) { Gettop(S,p); Pushstack(S,p->rchild); } } } } } } int main() { Bitree bt; Createbitree(bt); printf("递归先序遍历二叉树:\n"); Pretraverse(bt); printf("\n"); printf("非递归先序遍历二叉树:\n"); Preordertraverse(bt); printf("\n"); printf("递归中序遍历二叉树:\n"); Intraverse(bt); printf("\n"); printf("非递归中序遍历二叉树:\n"); Inordertraverse(bt); printf("\n"); printf("递归后序遍历二叉树:\n"); Posttraverse(bt); printf("\n"); printf("非递归后序遍历二叉树:\n"); Postordertraverse(bt); printf("\n"); return 0; } //ABD###CE##F##
时间: 2024-11-05 12:14:18