I created a class called BST and it has a member root. i know when i call a deconstructor to class BST it deletes root and frees memory occupied by the class.
I wanted to know that, will the deconstructor deconstruct all the nodes as well associated with the BST object. that is left child and right child of root and their left and right child and so on and so forth.
my guess is a No. in that case i think i will have to do a post order traversal and delete every node manually. is there any way to do it in once. without walking around the tree nodes
#ifndef BST_H
#define BST_H
#include "bst.h"
#include <stdio.h>
#include<iostream>
class bst
{
protected:
struct node{
node* p;
node* lc;
node* rc;
int key;
node(int x,node* p=nullptr,node* lc=nullptr,node* rc=nullptr):key(x){
}
~node(){
std::cout<<"decontrucotr node";
}
};
node* nil=new node(0);
node* root;
public:
bst();
virtual ~bst();
void put(int x);
void in_order(node* x);
void in_order();
void pre_order(node* x);
void pre_order();
private:
};
#endif // BST_H
functions are defined in this
#include "bst.h"
#include <stdio.h>
#include<iostream>
bst::bst():root(nil)
{
}
bst::~bst()
{
std::cout<<"deconstructor tree"<<'\n';
}
void bst::put(int x)
{
node* k=new node(x,this->nil,this->nil,this->nil);
node* y=this->root;
node* p=y;
while (y != nil){
p=y;
if (y->key>x){
y=y->lc;
}
else{
y=y->rc;
}
}
if (p==nil){
this->root=k;
k->lc=this->nil;
k->rc=this->nil;
k->p=this->nil;
}
else if(p->key>x){
p->lc=k;
p->lc->p=p;
k=p->lc;
k->lc=this->nil;
k->rc=this->nil;
}
else{
p->rc=k;
p->rc->p=p;
k=p->rc;
k->lc=this->nil;
k->rc=this->nil;
}
}
void bst::in_order(node* x){
if(x != nil){
this->in_order(x->lc);
printf("%d%c",x->key,'\t');
this->in_order(x->rc);
}
}
void bst :: in_order(){
this->in_order(this->root);
printf("%c",'\n');
}
void bst::pre_order(node* x){
if(x!=this->nil){
printf("%d%c",x->key,'\t');
pre_order(x->lc);
pre_order(x->rc);
}
}
void bst::pre_order(){
pre_order(this->root);
printf("%c",'\n');
}