c++ - Segmentation fault (core dumped) while creating binary tree of given height -
this first time working trees. wrote c++ code, says segmentation fault (core dumped)
, far searched, error comes accessing memory location may null. tried 'new' keyword malloc() should avoided in c++, still didn't how resolve in code.
# include<iostream> using namespace std; struct node { int data; node *left; node *right; }*next; int k=0; void tree(int i,/*struct*/ node *next = new node) { ++k; --i; if (i==0) return; //next = new node; next->data = k*k; next->left = null; next->right = null; tree(i, next->left); tree(i, next->right); return ; } void display (node* next) { cout<<next->data<<" "; if (next->left!=null) { display(next->left); display(next->right); } } int main() { int h; cout<<"enter expected height of tree : "; cin>>h; node *root; root = new node; root->data=0; root->left=null; root->right=null; tree(h, (root->left)); tree(h, (root->right)); cout<<root->data<<" "; display(root->left); display(root->right); return 0; }
#include <iostream> using namespace std; struct node { int data; struct node *left; struct node *right; }; void tree(int i, struct node **root, int k) { if (i < 1) return; *root = new struct node; (*root)->data = k*k; (*root)->left = null; (*root)->right = null; tree(i - 1, &((*root)->left), k + 1); tree(i - 1, &((*root)->right), k + 1); } void display(struct node *root) { if (root == null) return; cout << root->data << " "; if (root->left != null) display(root->left); if (root->right != null) display(root->right); } int main() { struct node *root; int h; cout<<"enter expected height of tree : "; cin>>h; tree(h, &root, 0); display(root); return 0; }
i think should more read on how pointers works: http://www.tutorialspoint.com/cprogramming/c_pointers.htm
when calling tree(h, root->left)
send pointers value "null" == 0x0. want allocate memory should send reference pointer. hence &root , &((*root)->left). in display function have check null values both left , right.
the code above improved , doesn't handle freeing of memory, able that, traverse tree , use delete on leafs , work root.
Comments
Post a Comment