1 #include 23using
namespace
std;
45 template 6
class
bst7
;16 node * root =nullptr;
17 node * putb(node *rootp, k key, v value); //
注意不能把這個函式放在公有區,因為node是乙個私有變數,如果外部呼叫putb會出問題,且只有成員函式會呼叫這個函式,沒必要宣告為公有的就不要宣告為公有
18public
:19 bst(/*
args
*/);
20void
puta(k key, v value);
21void
putb(k key, v value);
22/*
void putb(node *&rootp, k key, v value);
*///
類內定義結構體不用加作用域限定: bst::node
2324 v get
(k key);
25 v getr(node *rootp, k key); //
對於結構相似且頭尾相接的資料結構(如這裡的二叉樹:每個節點都可以是根節點,每個根節點下都有左右節點),要善於利用遞迴
26bool max(k &key, v &value);
27bool min(k &key, v &value);
28int
rank(k key);
29bool
remove(k key);
30int
howmany();
31void
show();
32void showr(node *p);
33void
free(node *p);
34 ~bst();
35};
3637 template 38 bst::bst(/*
args */)
3942
43 template 44 v bst::get
(k key)
4553}54
55 template 56 v bst::getr(node *rootp, k key)
5763
64if(rootp->key ==key)
65return rootp->value;
66else
if(rootp->key 6770
else
71return getr(rootp->left, key);72}
7374
/*迴圈查詢
*/75 template 76
void bst::puta(k key, v value)
7787
if((*temp)->key >key)
88 temp = &((*temp)->left);
89else
90 temp = &((*temp)->right);91}
92 *temp = (node *)new
node;
93 (*temp)->key =key;
94 (*temp)->value =value;95}
9697 template 98
void bst::putb(k key, v value)
99103
104/*
遞迴查詢
*/105
/*106
template
107void bst::putb(node *&rootp, k key, v value) //指標的引用
108116
if(rootp->key == key)
117121
else if(rootp->key > key)
122return putb(rootp->left, key, value);
123else
124return putb(rootp->right, key, value);
125126
}127
*/128
129/*
不加typename的話會提示錯誤: need 'typename' before 'bst::node' because 'bst' is a dependent scope,原因:c++primer p593
*/130 template 131 typename bst::node * bst::putb(node *rootp, k key, v value)
132140
if(rootp->key ==key)
141144
else
if(rootp->key >key)
145 rootp->left = putb(rootp->left, key, value);
146else
147 rootp->right = putb(rootp->right, key, value);
148149
return
rootp;
150}
151152 template 153
void bst::show()
154157
158 template 159
void bst::showr(node *p)
160167
168 template 169
void bst::free(node *p)
170177
178 template 179 bst::~bst()
180183
184int
main()
185196
197container.show();
198199
char
token;
200 cout << "
enter key you want to find(0 to exit):";
201 cin >>token;
202while(token != '0'
)203
208209
return0;
210 }
二叉樹 二叉查詢樹
構建二叉樹,判斷是否為二叉查詢樹,遞迴先序遍歷,非遞迴中序遍歷 include include include include using namespace std 二叉樹結點 struct treenode 鍊錶結點 struct listnode struct tempnodetempnode...
二叉樹 二叉查詢樹
二叉樹 binary tree 一種樹型結構,每個節點最多擁有兩個節點。如下圖 幾種型別的二叉樹 1.full binary tree 每個節點的孩子數 是 0 或者 2.對高度沒有要求。如下圖 2.perfect binary tree 這個就是最完美的樹,顧名思義,所有葉子節點都有相同的深度,並...
樹(樹,二叉樹,二叉查詢樹)
1.定義 n n 0 個結點構成的有限集合。當n 0時,稱為空樹 2.對於任一棵非空樹 n 0 它具備以下性質 1 樹中有乙個稱為 根 root 的特殊結點,用 r 表示 2 其餘結點可分為m m 0 個互不相交的有限集t1,t2,其中每個集合本身又是一棵樹,稱為原來樹的子樹。3.樹的一些性質 1 ...