您好,登錄后才能下訂單哦!
二叉樹是一種非線性結構,遍歷二叉樹幾乎都是通過遞歸或者用棧輔助實現非遞歸的遍歷。用二叉樹作為存儲結構時,取到一個節點,只
能獲取節點的左孩子和右孩子,不能直接得到節點的任一遍歷序列的前驅或者后繼。
為了保存這種在遍歷中需要的信息,我們利用二叉樹中指向左右子樹的空指針來存放節點的前驅和后繼信息。
enum PointerTag
{
LINK, //0
THREAD //1
};
template <typename T>
struct BitreeNodeTH
{
T Data;
BitreeNodeTH<T> *left; //左孩子
BitreeNodeTH<T> *right; //右孩子
PointerTag left_Tag; //左孩子線索標志
PointerTag right_Tag; //右孩子線索標志
BitreeNodeTH(T data = T())
:Data(data)
,left(NULL)
,right(NULL)
,left_Tag(LINK)
,right_Tag(LINK)
{}
};
一個線索二叉樹的節點:
left | left_Tag | Data | reght_Tag | reght |
線索化二叉樹的主要源代碼:
建樹:
BitreeNodeTH<T>* Create_tree(T *arr,int sz,int &i) { if(*arr==NULL||arr[i]=='#'||i>=sz) return NULL; else { BitreeNodeTH<T> *cur=new BitreeNodeTH<T>; cur->Data=arr[i]; i++; cur->left=Create_tree(arr,sz,i); i++; cur->right=Create_tree(arr,sz,i); return cur; } }
前序線索化:
void FirstOrderTH(BitreeNodeTH<T>* root, BitreeNodeTH<T>* &prev)// &表示沒有開辟臨時變量 { if (root == NULL) return; BitreeNodeTH<T>* cur = root; if (cur->left == NULL) { cur->left_Tag = THREAD; cur->left = prev; } if (prev&&prev->right == NULL) { prev->right_Tag = THREAD; prev->right = cur; } prev = cur; if (cur->left_Tag == LINK) //cur->left FirstOrderTH(cur->left,prev); if(cur->right_Tag == LINK) //cur->right FirstOrderTH(cur->right, prev); }
前序遍歷:
void FirstOrderTHing(BitreeNodeTH<T>* root) { if (root == NULL) return; BitreeNodeTH<T>* cur = root; while (cur) { while(cur->left_Tag == LINK) { cout<<cur->Data<<" "; cur = cur->left; } cout << cur->Data<<" "; if (cur->left_Tag == THREAD) { cur = cur->right; } } }
中序線索化:
void MidOrderTH(BitreeNodeTH<T>* root, BitreeNodeTH<T>* &prev) { if (root == NULL) return; BitreeNodeTH<T>* cur = root; MidOrderTH(cur->left,prev); if (cur->left == NULL) { cur->left_Tag = THREAD; cur->left = prev; } if (prev && prev->right == NULL) { prev->right = cur; prev->right_Tag = THREAD; } prev = cur; MidOrderTH(cur->right,prev); }
中序遍歷:
void MidOrderTHing(BitreeNodeTH<T>* root) { BitreeNodeTH<T>* cur = root; while(cur) { while (cur->left_Tag == LINK) { cur = cur->left; } cout<<cur->Data<<" "; while (cur->right_Tag == THREAD) { cur = cur->right; cout << cur->Data<< " "; } if (cur->right_Tag == LINK) { cur = cur->right; } } }
后序線索化:
void LaterOrderTH(BitreeNodeTH<T>* root, BitreeNodeTH<T>* &prev) { if (root == NULL) return; BitreeNodeTH<T>* cur = root; LaterOrderTH(cur->left,prev); LaterOrderTH(cur->right,prev); if (cur->left == NULL) { cur->left_Tag = THREAD; cur->left = prev; } if (prev&&prev->right == NULL) { prev->right = cur; prev->right_Tag = THREAD; } prev = cur; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。