有人可以幫我弄清楚如何正確刪除我的bst實現嗎?我知道這是一個簡單的問題,但我嘗試了一切。我想避免聲明一個動態數組,並且如果可以用這個指針結構保持代碼(不是雙關語意圖)。問題在於析構函數部分。謝謝 !如何刪除C++中的BST?
#include<iostream>
using namespace std;
struct Tree{
struct Tree* left;
struct Tree* right;
int val;
Tree(int);
~Tree();
void Print();
};
Tree::Tree(int val){
this->val = val;
cout<<"insert l/r for node: "<<this->val<<" , type 0 0 - exit" <<endl;
int l,r;
cin>>l>>r;
if(l and r){
this->left = new Tree(l);
this->right = new Tree(r);
}else if(l==0 and r==0){
this->left = NULL;
this->right = NULL;
return;
}
}
Tree::~Tree(){
if(this->left == NULL and this->right == NULL){
delete this;
return;
}else{
this->left->~Tree();
this->right->~Tree();
}
}
void Tree::Print(){
if(this == NULL) return;
cout<<this->val<<endl;
this->left->Print();
this->right->Print();
}
int main(){
int n;
cin>>n;
Tree* newT = new Tree(n);
newT->Print();
newT->~Tree();
//cout<<newT->val<<endl;
//newT->Print();
return 0;
}
我明白了,但我該如何釋放內存呢?如果我只是首先刪除對象newT,那麼我將無法訪問其子項。 – Valio
@ValentinKostadinov爲什麼你想要訪問孩子,如果你刪除樹? –
沒關係。多謝你們。我明白了,並會盡量避免這樣的錯誤。 – Valio