c++11 - C++ segmentation fault binary trees using pointers -


i have come implementation of binary tree ensures fillable positions in particular level filled ( number of nodes @ level k must 2^k before proceeding next level). unfortunately getting segmentation fault.

#include <iostream> #include <math.h> #define ll long long int using namespace std;  struct node {   int value=0;   node* left=null;   node* right=null;   int height=0;   int numnodes();    node()   {   }     node(int val,node* l=null,node* r=null) : value(val),left(l),right(r)  {}    int getheight();   node* operator=(node* n)  {   this->value=n->value;   this->right=n->right;   this->left=n->left;     }   }*binrooter;     int node::numnodes()    {     if(this->left==null && this->right==null)    return 0;     return this->left->numnodes()+this->right->numnodes()+1;     }     int node::getheight()    {     return max(this->left->getheight(),this->right->getheight())+1;    }     node* insertbintree(node* binrooter,ll num) {   if(binrooter==null)  return new node(num);   if(binrooter->value==num)  return null;   if(binrooter->left==null)  {   cout<<"inserting left"<<endl;   binrooter->left=new node(num);   }  else  if(binrooter->right==null)  {   cout<<"inserting right"<<endl;   binrooter->right=new node(num);   }   else   {   int k=binrooter->getheight();   int numchild=pow(2,k);   if(binrooter->numnodes()==numchild-1)   numchild=pow(2,k+1);          if(binrooter->left->numnodes()>numchild/2)   {    cout<<"traversing right"<<endl;    binrooter->right=insertbintree(binrooter->right,num);    }    else   {    cout<<"traversing left"<<endl;    binrooter->left=insertbintree(binrooter->left,num);    }    }     return binrooter;     }      void insertbintree(ll num)  {     binrooter=insertbintree(binrooter,num);   }       void print(node *root) {  if(root!=null) {  print(root->left);  cout<<root->value<<" ";  print(root->right); } }     int main()    {    ll num=0;      {   cout<<endl<<"enter element inserted or enter -1"<<endl;   cin>>num;   if(num==-1)  {   break;  }   insertbintree(num);   }  while(num!=-1);   cout<<"printing tree in sorted order"<<endl;  print(rooter);  } 

the problem if try insert more 3 nodes, segmentation fault. kind of figured out error lies somewhere in using getheight() insert in leftsubtree or rightsubtree, can't pinpoint error

your getheight function recursive. youve given no stop case. recurse down tree until hits null.

you must test this->left && this->right !null before making recursive call


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -