您好,登錄后才能下訂單哦!
二叉樹是一種非線性結(jié)構(gòu),遍歷二叉樹幾乎都是通過遞歸或者用棧輔助實(shí)現(xiàn)非遞歸的遍歷。用二叉樹作為存儲(chǔ)結(jié)構(gòu)時(shí),取到一個(gè)節(jié)點(diǎn),只能獲取節(jié)點(diǎn)的左孩子和右孩子,不能直接得到節(jié)點(diǎn)的任一遍歷序列的前驅(qū)或者后繼。
為了保存這種在遍歷中需要的信息,我們利用二叉樹中指向左右子樹的空指針來存放節(jié)點(diǎn)的前驅(qū)和后繼信息。
代碼結(jié)構(gòu)如下:
enum PointerTag { THREAD, LINK }; template<class T> struct BinaryTreeNode { T _data; BinaryTreeNode<T>* _left; BinaryTreeNode<T>* _right; PointerTag _leftTag;//左孩子線索標(biāo)志 PointerTag _rightTag;//右孩子線索標(biāo)志 BinaryTreeNode(const T& d) :_data(d) , _left(NULL) , _right(NULL) { _leftTag = LINK; _rightTag = LINK; } };
代碼實(shí)現(xiàn)如下:
void InOrderThreading() //中序線索化 { Node* prev = NULL; _InOrderThreading(_root, prev); } void PrevOrderThreading() //前序線索化 { Node* prev = NULL; _PrevOrderThreading(_root, prev); } //void PostOrderThreading() //后序線索化 //{ // Node* prev = NULL; // _PostOrderThreading(_root, prev); //} void InOrderThd() //中序遍歷 { Node* cur = _root; while (cur) { while (cur->_leftTag == LINK) { cur = cur->_left; } cout << cur->_data << " "; while (cur->_rightTag == THREAD) { cur = cur->_right; cout << cur->_data << " "; } cur = cur->_right; } cout << endl; } void PrevOrderThd() //前序遍歷 { Node* cur = _root; while (cur) { cout << cur->_data << " "; while (cur->_leftTag == LINK) { cur = cur->_left; cout << cur->_data << " "; } cur = cur->_right; } cout << endl; } void _InOrderThreading(Node* root, Node*& prev) // { if (root == NULL) { return; } _InOrderThreading(root->_left, prev); if (root->_left == NULL) { root->_leftTag = THREAD; root->_left = prev; } if (prev&&(prev->_right == NULL)) { prev->_rightTag = THREAD; prev->_right = root; } prev = root; _InOrderThreading(root->_right, prev); } void _PrevOrderThreading(Node* root, Node*& prev) { Node* cur = root; if (cur == NULL) { return; } if (cur->_left == NULL) { cur->_leftTag = THREAD; cur->_left = prev; } if (prev&&prev->_right == NULL) { prev->_rightTag = THREAD; prev->_right = cur; } prev = cur; if (cur->_leftTag == LINK) { _PrevOrderThreading(cur->_left, prev); } if (cur->_rightTag == LINK) { _PrevOrderThreading(cur->_right, prev); } }
因?yàn)楹笮虮容^復(fù)雜,所以露珠不是很有能力寫出來。以后露珠會(huì)好好提高自己,然后把后序?qū)崿F(xiàn)了哈哈哈哈
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。