c++ - create a BST of string . error -
inserting 1 node tree works fine, on inserting 2nd node onwards, program crashes. here code:
#include <iostream> #include <cstring> using namespace std; struct node { char* key; node *left, *right; }; // utility function create new bst node node *newnode(const char* item) { node *temp =new node; strcpy(temp->key,item); temp->left = temp->right = null; return temp; } // utility function inorder traversal of bst void inorder(node *root) { if (root!= null) { inorder(root->left); cout<<root->key<<endl; inorder(root->right); } } /* utility function insert new node given key in bst */ node* insert(node* tnode,const char* key) { /* if tree empty, return new node */ if (tnode == null) return newnode(key); /* otherwise, recur down tree */ if (strcmp(key,tnode->key) < 0) tnode->left = insert(tnode->left, key); else if (strcmp(key,tnode->key) > 0) tnode->right = insert(tnode->right, key); /* return (unchanged) node pointer */ return tnode; } // driver program test above functions*/ int main() { node *root = null; char* word[]={"elephant","hi","little","nil",null}; root = insert(root,word[0]); //works fine for(int i=1;word[i];i++) insert(root,word[i]); // print inoder traversal of bst inorder(root); return 0; }
after:
root = insert(root,word[0]);
inorder(root);
o/p: elephant
on inserting 2nd node
crashes
you're not initialising key
array item
copied into. try this:
node *newnode(const char* item) { node *temp = new node(); temp->key = new char[strlen(item) + 1]; strcpy(temp->key,item); temp->left = temp->right = null; return temp; }
that said, there more problems code, no destructors etc. i'd recommend reading books/tutorials on programming in c++.
Comments
Post a Comment