2015-04-25 53 views
-2

只插入一個節點到樹上工作正常,但在插入第二個節點之後,程序崩潰。下面是代碼:創建一個字符串BST。錯誤

#include <iostream> 
#include <cstring> 

using namespace std; 
struct node 
{ 
    char* key; 
    node *left, *right; 
}; 

// A utility function to create a new BST node 
node *newNode(const char* item) 
{ 
    node *temp =new node; 
    strcpy(temp->key,item); 
    temp->left = temp->right = NULL; 
    return temp; 
} 

// A utility function to do inorder traversal of BST 
void inorder(node *root) 
{ 
    if (root!= NULL) 
    { 
     inorder(root->left); 
     cout<<root->key<<endl; 
     inorder(root->right); 
    } 
} 

/* A utility function to insert a new node with given key in BST */ 
node* insert(node* tnode,const char* key) 
{ 
    /* If the tree is empty, return a new node */ 

    if (tnode == NULL) 
     return newNode(key); 
    /* Otherwise, recur down the 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 the (unchanged) node pointer */ 
    return tnode; 
} 

// Driver Program to 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 the BST 
    inorder(root); 

    return 0; 
} 

後:

根=插入件(根,字[0]);

inorder(root);

O/P:在插入第二個節點

崩潰

+0

請用適當的語法編輯你的問題。添加解釋代碼的含義以及實際結果。 –

+0

對不起。 這是我的第一篇文章 –

回答

0

你沒有初始化的key陣列item將會被複制到大象

。試試這個:

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; 
} 

這就是說,有一些更多的問題與您的代碼,就像沒有析構函數等,我強烈建議你閱讀上編程的一些好的書籍/教程C++。

+0

謝謝,它的工作。是的,我會進一步改進 –