線索二叉樹

2021-09-01 08:34:23 字數 1902 閱讀 1968

1.演算法描述

2.演算法說明

具體說明有四點:如下圖

注:尤其要注意第4點,我在寫的時候就沒注意這個問題,結果遍歷的時候出現了無限迴圈,找了半天才找到!主要是建立二叉樹判斷的慣性思維,故而容易出現錯誤!

3.**實現

標頭檔案

#ifndef bithrtree_h

#define bithrtree_h

enum flag;//列舉型別,列舉常量child=0,thread=1

templatestruct node;

templateclass bithrtree;

#endif

bithrtree.cpp

標//就是容易出錯的地方!!

#include #include "bithrtree.h"

using namespace std;

templatebithrtree::bithrtree()

templatebithrtree::~bithrtree()

//獲取根結點

templatenode* bithrtree::getroot( )

//查詢結點p的中序後繼結點

templatenode* bithrtree::next(node* p)

return t;

}else

}//中序遍歷線索鍊錶

templatevoid bithrtree::inorder(node* root)

//開始中序遍歷

dowhile(root);

}}

//查詢結點p的中序前驅結點

templatenode* bithrtree::inprenode(node* p)else

return t; }}

//查詢結點x

templatenode* bithrtree::searchnode(t x)

//開始中序遍歷

doroot = next(root);

}while(root);

} return t;

} //建立二叉樹

templatevoid bithrtree::creatthrtree(node* &root)

}

//二叉樹的線索化(中序線索二叉樹)

templatevoid bithrtree::bithrtree(node* &root, node* &pre)else

//右孩子處理(rflag不能處理後序,因為還沒遍歷到)

if(!root->rchild)else

//pre的後續(rflag之前已經處理,如果設定為了索引,設定右索引為root)

if(pre)

////記錄前驅

pre = root;

bithrtree(root->rchild, pre); }}

//析構函式呼叫

templatevoid bithrtree::release(node* root)

}

main.cpp

#include #include #include "bithrtree.cpp"

using namespace std;

int main(){

bithrtreebt;

node* t = bt.getroot();

cout<

cout<

r = bt.searchnode("b");

if(r) cout

基本上只要明白了二叉樹的基本原理,線索二叉樹就非常的簡單,就多了乙個線索化的過程,簡化了搜尋前序和後繼結點的時間,提高了效率!

如果有什麼不對的地方,歡迎指正!

線索二叉樹

當用二叉鍊錶作為二叉樹的儲存結構時,因為每個結點中只有指向其左 右兒子結點的指標,所以從任一結點出發只能直接找到該結點的左 右兒子。在一般情況下靠它無法直接找到該結點在某種遍歷序下的前驅和後繼結點。如果在每個結點中增加指向其前驅和後繼結點的指標,將降低儲存空間的效率。我們可以證明 在n個結點的二叉鍊...

線索二叉樹

1.線索二叉樹結構和操作定義 threadbintree.h 功能 線索標誌域所有值 typedef enumnodeflag 功能 線索二叉樹結構體 typedef struct threadtreethreadbintree 前驅節點指標 threadbintree previous null ...

線索二叉樹

原始碼 中序線索二叉樹 author 菜鳥 version 2014.7.23 include include include typedef char datatype using namespace std 定義線索二叉樹的結構體 typedef struct nodethreadbitreen...