2015-04-25 54 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

谢谢,它的工作。是的,我会进一步改进 –