1. 程式人生 > >遍歷二叉樹-遞迴和非遞迴演算法

遍歷二叉樹-遞迴和非遞迴演算法

// 二叉樹節點 typedef struct Bitree { char data; struct Bitree *lchild, *rchild; }Bitree; // 新節點 Bitree *new(char data) { Bitree *a = (Bitree *)malloc(sizeof(Bitree)); a->data = data; a->lchild = NULL; a->rchild = NULL; return a; } // 中序遍歷二叉樹的遞迴演算法 void inorder(Bitree *t) { if (t) { inorder(t->lchild); printf("%c ", t->data); inorder(t->rchild); } } // 前序遍歷二叉樹的遞迴演算法 void preorder
(Bitree *t) { if (t) { printf("%c ", t->data); preorder(t->lchild); preorder(t->rchild); } } // 後序遍歷二叉樹的遞迴演算法 void postorder(Bitree *t) { if (t) { postorder(t->lchild); postorder(t->rchild); printf("%c ", t->data); } } // 前序遍歷二叉樹的非遞迴演算法 void preorder2(Bitree *t) { Bitree *s[32]; // s是指標陣列,陣列中元素為二叉樹節點的指標 int top = -1; while (t!=NULL || top != -1) { // 壓棧直到左子樹為空 while (t != NULL) { printf("%c ", t->data); s[++top] = t; t = t->lchild; } if (top != -1) { t = s[top--]; // 出棧 t = t->rchild; // 指向該節點的右孩子,回到while迴圈壓棧 } } } // 中序遍歷二叉樹的非遞迴演算法 void inorder2
(Bitree *t) { Bitree *s[32]; // s是指標陣列,陣列中元素為二叉樹節點的指標 int top = -1; while (t!=NULL || top != -1) { // 壓棧直到左子樹為空 while (t != NULL) { s[++top] = t; t = t->lchild; } if (top != -1) { t = s[top--]; // 出棧 printf("%c ", t->data); t = t->rchild; // 指向該節點的右孩子,回到while迴圈壓棧 } } } // 後序遍歷二叉樹的非遞迴演算法 void postorder2
(Bitree *t) { Bitree *s[32]; // s是指標陣列,陣列中元素為二叉樹節點的指標 int tag[32]; // s中相對位置的元素的tag: 0或1 int top = -1; while (t!=NULL || top != -1) { // 壓棧直到左子樹為空 while (t != NULL) { s[++top] = t; tag[top] = 0; t = t->lchild; } // 當棧非空,並且棧頂元素tag為1時,出棧並訪問 while (top!=-1 && tag[top]==1) { printf("%c ", s[top--]->data); } // 當棧非空時,將棧頂tag置1,並指向棧頂元素的右孩子 if (top != -1) { tag[top] = 1; t = s[top]->rchild; } } } int main() { // 申請空間構造一棵二叉樹 Bitree *a = new('A'); Bitree *b = new('B'); Bitree *c = new('C'); Bitree *d = new('D'); Bitree *e = new('E'); Bitree *f = new('F'); a->lchild = b; a->rchild = c; b->lchild = d; b->rchild = e; c->rchild = f; // 遞迴演算法 printf("preorder: "); preorder(a); printf("/n"); printf("inorder: "); inorder(a); printf("/n"); printf("postorder: "); postorder(a); printf("/n"); printf("/n"); // 非遞迴演算法 printf("preorder2: "); preorder2(a); printf("/n"); printf("inorder2: "); inorder2(a); printf("/n"); printf("postorder2: "); postorder2(a); printf("/n"); free(a); free(b); free(c); free(d); free(e); free(f); return 0; }