我目前正在學習如何實現二叉搜索樹,但使用更基本的C方法(請不要「現在使用類」)。但是,動態內存自身刪除存在很大的問題。頭值得到正確更新,但是,其他每一點都會被刪除。誰能幫我?另外,如果你會提供一些技巧來強化我的樹的實現,那將是很好的。該程序的基本概要:您輸入一個字符,然後運行其中一個樹的功能。但是請注意,這個實現是一個純粹的BST,所以沒有平衡。謝謝。二叉搜索樹C++實現(動態內存問題)
#include <iostream>
struct point{
point* parent, *left, *right;
int val = -1;
};
point* biggest;
point empty;
point search(int pos, bool near, point* loc = biggest){
if(loc->val == pos){
return *loc;
} else if(loc->left->val != -1 and loc->val > pos){
return search(pos, near, loc->left);
} else if(loc->right->val != -1){
return search(pos, near, loc->right);
}
if(near){
return *loc;
} else{
point fail;
return fail;
}
}
void insert(int pos, point* res){
point loc = search(pos, true);
res->val = pos, res->left = &empty, res->right = &empty, res->parent = &loc;
if(loc.val < res->val){
loc.left = res;
} else{
loc.right = res;
}
}
void remove(int pos){
}
int pred(int pos){
point res = search(pos, false);
if(res.val == -1){
return -1;
}
}
int succ(int pos){
point res = search(pos, false);
if(res.val == -1){
return -1;
}
}
void inorder(point* pos = biggest){
if(pos->left->val != -1){
inorder(pos->left);
}
std::cout << pos->val << " ";
if(pos->right->val != -1){
inorder(pos->right);
}
}
int main() {
point start;
start.parent = &empty, start.left = &empty, start.right = ∅
biggest = &start;
char c;
int pos;
do{
std::cin >> c >> pos;
switch (c){
case 'S':
std::cout << search(pos, false).val << std::endl;
break;
case 'I':
if(biggest->val == -1){
start.val = pos;
} else{
point* res = new point;
insert(pos, res);
}
break;
case 'R':
remove(pos);
break;
case 'P':
std::cout << pred(pos) << std::endl;
break;
case 'N':
std::cout << succ(pos) << std::endl;
break;
case 'O':
inorder();
std::cout << std::endl;
break;
}
} while(c != '0');
return 0;
}
'point * res = new point;' 樹應該負責創建節點,而不是'main()'。如果用戶正在完成數據結構應負責的大量工作,那麼數據結構有什麼好處? – PaulMcKenzie 2015-03-31 21:43:38
@PaulMcKenzie我嘗試的第一件事是由函數完成的「構造」。我將其改爲一個可能不太合理的構造函數,然後將其更改爲此代碼。 – ReaLNero 2015-04-01 17:02:41