以下这份代码是一个简陋的二叉树实现:
namespace TREE{
struct Node{
Node *ls, *rs;
int val;
Node(){
ls = rs = nullptr;
val = 0;
}
Node(int v): val(v){
ls = rs = nullptr;
}
~Node();
void print(){
if(ls) ls->print();
printf("%d ", val);
if(rs) rs->print();
}
};
struct Tree{
Node * root;
Tree(){
root = nullptr;
}
~Tree(){
//TODO
}
void insert(int);
void delt(int);
void print();
};
void Tree::insert(int v){
if(!root){
root = new Node(v);
}
else{
Node * t = root;
Node * p = nullptr;
while (t)
{
p = t;
if (v > root->val) t = root->rs;
else t = root->ls;
}
t = new Node(v);
if (p->val > t->val) p->ls = t;
else p->rs = t;
}
}
void Tree::delt(int v){
//TODO
}
void Tree::print(){
if(!root) return;
root->print();
}
}
using namespace TREE;
int main(){
Tree T;
T.insert(1);
T.insert(2);
T.insert(-1);
T.print();
return 0;
}
一般来说,new 和 delete 需配套使用,那么在 TODO 的地方怎样使用 delete?