1. 程式人生 > 實用技巧 >二叉樹遍歷

二叉樹遍歷

/*二叉樹前序、中序、層次層次遍歷*/
#include<stdio.h> #include<malloc.h> typedef char ElemType; typedef struct BiTNode { ElemType val; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; typedef struct LinkNode { BiTNode *data; struct LinkNode *next; }LinkNode; typedef struct { LinkNode *front,*rear; }LinkQueue; void InitQueue(LinkQueue &Q) //初始化佇列 { Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode)); Q.front->next=NULL; } bool EmptyQueue(LinkQueue Q) //判斷佇列是否為空 { if(Q.rear==Q.front) return true; else return false; } void EnQueue(LinkQueue &Q,BiTree p) //樹節點入隊 { LinkNode *q; q=(LinkNode *)malloc(sizeof(LinkNode)); q->data=p; q->next=NULL; Q.rear->next=q; Q.rear=q; } bool DeQueue(LinkQueue &Q,BiTree &p) //樹節點出隊 { if(EmptyQueue(Q)) return false; LinkNode *q=Q.front->next; p=q->data; Q.front->next=q->next; if(Q.rear==q) Q.rear=Q.front; free(q); return true; } BiTree IniTree() //初始化樹 { BiTree t; char ch; ch=getchar(); if(ch == '#') t=NULL; else { t=(BiTree)malloc(sizeof(BiTNode)); t->val=ch; t->lchild=IniTree(); t->rchild=IniTree(); } return t; } void visit(BiTree T) //訪問樹節點 { printf("%c",T->val); } bool proOrder(BiTree T) //先序遍歷 { if(T==NULL) return false; else { visit(T); proOrder(T->lchild); proOrder(T->rchild); } return true; } bool inOrder(BiTree T) //中序遍歷 { if(T==NULL) return false; else { inOrder(T->lchild); visit(T); inOrder(T->rchild); } } bool postOrder(BiTree T) //後序遍歷 { if(T==NULL) return false; else { postOrder(T->lchild); postOrder(T->rchild); visit(T); } } void LevelOrder(BiTree T) //層次遍歷 { LinkQueue Q; InitQueue(Q); BiTree p; if (T!=NULL) EnQueue(Q,T); //根節點入隊 while(!EmptyQueue(Q)) { DeQueue(Q,p); //隊頭節點出隊 visit(p); if(p->lchild!=NULL) EnQueue(Q,p->lchild); //左子樹不空,左子樹根節點入隊 if(p->rchild!=NULL) EnQueue(Q,p->rchild); //右子樹不空,右子樹根節點入隊 } } void main() { BiTree T; printf("按先序序列輸入結點序列,'#'代表空: "); T=IniTree(); printf("\n先序遍歷:"); proOrder(T); printf("\n中序遍歷:"); inOrder(T); printf("\n後序遍歷:"); postOrder(T); printf("\n層次遍歷:"); LevelOrder(T); printf("\n"); }
/*感謝一位陌生大佬的幫助*/