中序線索化及遍歷
阿新 • • 發佈:2022-04-04
終於把二叉樹搞完了
跟著王道的課走了幾遍,終於把中序線索樹的生成和遍歷搞定了,這玩意做題思路還挺清晰,寫程式碼真是折磨人啊
#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node* pleft; struct Node* pright; int tagleft; int tagright; }node, * pnode; node *pre = NULL; void inthread(pnode T) { if (T != NULL) { inthread(T->pleft); visit(T); inthread(T->pright); } } void visit(pnode p)//中序線索化 { if (p->pleft==NULL) { p->pleft = pre; p->tagleft = 1; } if (pre != NULL && pre->tagright==NULL) { pre->pright = p; pre->tagright = 1; } pre = p; //此時pre指向最後一個節點 //在呼叫時,最後需要將pre的右指標置為null } pnode findnext(pnode p) { if (p->tagright == 1)//p沒有右節點,右節點存放的就是下個節點 { return p->pright; } else { while (p->tagleft == 0)p = p->pleft;//找到最左的節點 } return p; }