遍历二叉数
(1)递归的方式递归二叉数
#include <stdio.h> #include <stdlib.h> typedef struct node { char data; struct node *lchild; struct node *rchild; }Node; void creatBT(Node* T) { char ch; scanf("%c", &ch); if ('.'==ch) { return; } else { T=(Node *)malloc(sizeof(Node)); if (T==NULL) { exit(0); } T->data=ch; creatBT(T->lchild); creatBT(T->rchild); } } void pre_order(Node* T) { if (T) { printf("%c ", T->data); pre_order(T->lchild); pre_order(T->rchild); } } void mid_order(Node* T) { if (T) { pre_order(T->lchild); printf("%c ", T->data); pre_order(T->rchild); } } void behind_order(Node* T) { if (T) { pre_order(T->lchild); pre_order(T->rchild); printf("%c ", T->data); } } int main() { Node *T; printf("请输按先序序列输入一串字符,当子树为空时, 用.来代替\n"); /* 创建二叉数 */ creatBT(T); printf("建树成功,T指向二叉树的根!\n"); /* 前序遍历*/ printf("\n前序遍历二叉树的结果是:"); pre_order(T); /* 中序遍历*/ printf("\n中序遍历二叉树的结果是:"); mid_order(T); /* 后序遍历*/ printf("\n后序遍历二叉树的结果是:"); behind_order(T);printf("\n"); return 0; }
(2)非递归遍历二叉数
#include <iostream> using namespace std; typedef struct node { char data; struct node* lchild; struct node* rchild; }bintnode; typedef struct stack { bintnode* data[100]; int tag[100]; int top; }seqstack; void push(seqstack* s,bintnode* t) { s->data[s->top]=t; ++s->top; } bintnode* pop(seqstack* s) { if(s->top!=-1) { s->top--; return (s->data[s->top+1]); } else return NULL; } void createbintree(bintnode* t) { char ch; if((ch=getchar())=='.') { t=NULL; } else { t=(bintnode*)malloc(sizeof(bintnode)); t->data=ch; createbintree(t->lchild); createbintree(t->rchild); } } void preorder(bintnode* t) { seqstack s; s.top=-1; while((t)||(s.top!=-1)) { while(t) { cout<<t->data<<" "; s.top++; s.data[s.top]=t; t=t->lchild; } if(s.top>-1) { t=pop(&s); t=t->rchild; } } } void inorder(bintnode* t) { seqstack s; s.top=-1; while((t!=NULL)||(s.top!=-1)) { while(t) { push(&s,t); t=t->lchild; } if(s.top!=-1) { t=pop(&s); cout<<t->data<<" "; t=t->rchild; } } } void postorder(bintnode* t) { seqstack s; s.top=-1; while((t)||(s.top!=-1)) { while(t) { s.top++; s.data[s.top]=t; s.tag[s.top]=0; t=t->lchild; } while((s.top>-1)&&(s.tag[s.top]==1)) { t=s.data[s.top]; cout<<t->data<<" "; s.top--; } if(s.top>-1) { t=s.data[s.top]; s.tag[s.top]=1; t=t->rchild; } else t=NULL; } } int main() { bintnode* tree; cout<<"输入根结点:"; createbintree(tree); cout<<"\n前序非递归遍历二叉树:"; preorder(tree); cout<<"\n-----------------------------\n"; cout<<"\n中序非递归遍历二叉树:"; inorder(tree); cout<<"\n----------------------------\n"; cout<<"\n后序非递归遍历二叉树:"; postorder(tree); cout<<endl; }