您好,登錄后才能下訂單哦!
這篇“如何用C語言遞歸實現線索二叉樹”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“如何用C語言遞歸實現線索二叉樹”文章吧。
描述:將二叉樹中結點的空左孩子指針域指向前驅結點,將空的右孩子指針域指向后繼結點。
code:
#pragma warning(disable:4996) #include<stdio.h> #include<stdlib.h> typedef struct TreeNode { char data; struct TreeNode *lchild, *rchild; int ltag, rtag; }Tree,*BTree; BTree Build_Tree(void) { BTree T; char ch; scanf("%c", &ch); if (ch == '#') { T = NULL; } else { T = (BTree)malloc(sizeof(Tree)); T->data = ch; T->ltag = 0; T->rtag = 0; T->lchild = Build_Tree(); T->rchild = Build_Tree(); } return T; } //先序線索化 void Pre_Thread(BTree cur, BTree *pre) { if (cur && cur->ltag==0) { printf("%c ", cur->data); if (cur->lchild == NULL) { cur->lchild = *pre; (*pre)->ltag = 1; cur->ltag = 1; } if (cur->rchild == NULL) { cur->rtag = 1; } if (*pre && (*pre)->rtag == 1) { (*pre)->rchild = cur; } *pre = cur; Pre_Thread(cur->lchild, pre); Pre_Thread(cur->rchild, pre); } } //中序線索化 void In_Thread(BTree cur, BTree *pre) { if (cur) { In_Thread(cur->lchild, pre); printf("%c ", cur->data); if (cur->lchild==NULL) { cur->lchild = *pre; cur->ltag = 1; } if (cur->rtag == NULL) { cur->rtag = 1; } if (*pre && (*pre)->rtag == 1) { (*pre)->rchild = cur; } *pre = cur; In_Thread(cur->rchild, pre); } } //后序線索化 void Post_Thread(BTree cur, BTree *pre) { if (cur) { Post_Thread(cur->lchild, pre); Post_Thread(cur->rchild, pre); printf("%c ", cur->data); if (cur->lchild == NULL) { cur->lchild = *pre; cur->ltag = 1; } if (cur->rchild == NULL) { cur->rtag = 1; } if (*pre && (*pre)->rtag == 1) { (*pre)->rchild = cur; } *pre = cur; } } int main(void) { BTree T,p=NULL; T = Build_Tree(); Pre_Thread(T, &p); //In_Thread(T, &p); //Post_Thread(T, &p); return 0; }
以上就是關于“如何用C語言遞歸實現線索二叉樹”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。