algorithm - C++ Binary Search Tree Implementation -


i working on project in c++ in have create binary search tree inserts items array. have use following insert algorithm:

tree-insert(t, z)

y = nil x = t.root while x != nil     y = x     if z.key < x.key         x = x.left     else x = x.right z.p = y if y == nil     t.root = z else if z.key < y.key     y.left = z else y.right = z 

here have far:

#include <iostream> using namespace std;  struct node {     int key;     node* left;     node* right;     node* p;     node* root; };  void insert(node*, node*); void printinorder(node*);  int main() {     node *root;     node* tree = new node;     node* z = new node;     int array [10] = {30, 10, 45, 38, 20, 50, 25, 33, 8, 12};      (int = 0; < 10; i++)     {         z->key = array[i];         insert(tree, z);     }      printinorder(tree);      return 0; }  void insert(node *t, node *z) {     node *y = nullptr;     node* x = new node;     x = t->root;     while (x != null)     {         y = x;         if (z->key < x->key)             x = x->left;         else             x = x->right;     }     z->p = y;     if (y == null)         t->root = z;     else if (z->key < y->key)         y->left = z;     else         y->right = z; }  void printinorder(node *x) {     if (x != null)     {         printinorder(x->left);         cout << x->key << endl;         printinorder(x->right);     } }     

this code compiles when run it, seg faults. believe problem has nodes creating or function calls. help.

besides issues noted in comments, biggest bug in code lack of constructor initializes pointers in new node null.

as such, every node create have pointers containing random garbage. code initializes of them, not. trying use uninitialized pointers result in immediate crash.

you need fix problems have been noted in comments, , have proper constructor node class.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -