创建一个字符串的BST。错误

时间:2015-04-25 20:15:47

标签: c++ data-structures binary-search-tree

只向树中插入一个节点可以正常工作,但是在向前插入第二个节点时,程序崩溃了。这是代码:

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

后:

root = insert(root,word [0]);

序(根);

o / p:elephant

插入第二个节点

崩溃

1 个答案:

答案 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 ++编程的好书/教程。