缺少非递归后续遍历
#include <iostream> #include <cstdio> #include <malloc.h> #include <stack> using namespace std; typedef struct tree{ char a; tree *lchild; tree *rchild; }; tree* create(tree *T){ char c=getchar(); if(c=='#'){ T=NULL; }else{ T=(tree*)malloc(sizeof(tree)); T->a=c; if(!T){ printf("Error!n"); } T->lchild=create(T->lchild); T->rchild=create(T->rchild); } return T; } void preorder(tree *T){ if(T){ printf("%c",T->a); preorder(T->lchild); preorder(T->rchild); } } void inorder(tree *T){ if(T){ inorder(T->lchild); printf("%c",T->a); inorder(T->rchild); } } void postorder(tree *T){ if(T){ postorder(T->lchild); postorder(T->rchild); printf("%c",T->a); } } //非递归先序遍历 void preorder1(tree *T){ tree *p=T; stack<tree *> s; while(p!=NULL||!s.empty()){ while(p!=NULL){ printf("%c",p->a); s.push(p); p=p->lchild; } if(!s.empty()){ p=s.top(); s.pop(); p=p->rchild; } } } //非递归中序遍历 void inorder1(tree *T){ tree *p=T; stack<tree *> s; while(p!=NULL||!s.empty()){ while(p!=NULL){ s.push(p); p=p->lchild; } if(!s.empty()){ p=s.top(); printf("%c",p->a); s.pop(); p=p->rchild; } } } //非递归后序遍历 int main() { tree *T; printf("Plese input the tree's sequence: "); T=create(T); printf("preorder: "); preorder(T); printf(" "); printf("inorder: "); inorder(T); printf(" "); printf("postorder: "); postorder(T); printf(" "); printf("preorder(no_recersive): "); preorder1(T); printf(" "); printf("inorder(no_recersive): "); inorder1(T); printf(" "); return 0; }