I’ve been working on the input from file and think I have the logic right, but my nodes aren’t linking properly. I’m able to set the root correctly and the program is able to walk through the string and load the nodes properly, just not link them. Can anyone help me sort through my logic and figure out the problem?
The input string is (A (B (D G) E) (C () F)).
struct node
{
string data;
node* left;
node* right;
};
void tree::build_tree(string &input, int i, node *n)
{
if(i > input.length())
return *n = NULL;
if(input[i] == '(')
{
string data; string temp;
int prev_i = i;
//get_data retrieves the identifier
data = get_data(input, temp, i+1);
//get_data_num retrieves the new position in the string
i = get_data_num(input, temp, i+1);
if(input[prev_i] == '('&& input[i] == ')')
{
i += 1;
*n = NULL;
}
else
{
// Allocate a new node and assign the data and
// set the pointer to the branches to null
*n = new node;
(*n)->data = data;
(*n)->left = NULL;
(*n)->right = NULL;
if(input[i] == ' ')
{i += 1; }
//Pass the address of the nodes
build_tree(input, i, &(*n)->left);
build_tree(input, i, &(*n)->right);
}
}
else if(isalnum(input[i]) || input[i] == '_' || input[i] == '-')
{
string data; string temp;
int prev_i = i;
data = get_data(input, temp, i);
i = get_data_num(input, temp, i);
if(input[prev_i] == '('&& input[i] == ')')
{
i += 1;
*n = NULL;
}
else
{
*n = new node;
(*n)->data = data;
(*n)->left = NULL;
(*n)->right = NULL;
if(input[i] == ' ')
{ i += 1; }
build_tree(input, i, &((*n)->left));
build_tree(input, i, &((*n)->right));
}
}
else if(input[i] == ' ')
{
i += 1;
}
else if(input[i] == ')')
{
i += 1;
*n = NULL;
}
else
{
cout << "The input tree is not in the correct format!" << endl;
}
}
I believe the issue is that you are not setting the value of the left and right pointers. You are passing the values of the pointers. You need to pass a pointer to the pointers (left and right), to set the value in the structure. The other alternative is to use references instead of pointers.
Here are the modifications I came up with for the code you supplied:
a pointer.
get a pointer to a pointer).
call the build_tree you need to pass in the address of root. This
will set the node just like all of the nodes which follow, so it does not need
to be a special case.
branch (may not need to do this, but I feel it is good practice to
make sure all items have some initial values).
Then for the initial call,
build_tree(testString,0,&root);
Since the get_data and get_data_num were not supplied, I was not able to test the changes which were made.