I am trying to add element in a Set using Binary Tree:
bool TreeSet::add(const string &str)
{
if (treesize == 0)
{
TreeNode->data = str;
treesize++;
return true;
}
else
{
if (str < TreeNode->data)
return insert(TreeNode->left, str);
else if (str > TreeNode->data)
return insert(TreeNode->right, str);
else
return false;
}
return false;
}
bool TreeSet::insert(TREE *node, const string &str) //private
{
if (node == NULL)
{
node = new TREE;
node->data=str;
node->left = NULL;
node->right = NULL;
treesize++;
return true;
}
else
{
if (str < node->data)
return insert(node->left, str);
else if (str > node->data)
return insert(node->right, str);
else
return false;
}
return false;
}
As you can see, I want to initialize a TREE struct inside of insert and when I finish doing this I want to link it with the left or right node of the tree.
But when I gdb this, only 1 level of tree (top level) can be constructed, the *left
and *right
node are NULL
no matter how many strings I was trying to add to it. Why?
My TREE is:
typedef struct tree
{
string data;
tree *left;
tree *right;
} TREE;