我一直在处理来自文件的输入,并认为我的逻辑正确,但我的节点没有正确链接。我能够正确设置root,程序能够遍历字符串并正确加载节点,而不是链接它们。任何人都可以帮助我梳理我的逻辑并找出问题吗?
输入字符串是(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;
}
}
答案 0 :(得分:0)
我认为问题在于你没有设置左右指针的值。您正在传递指针的值。您需要将指针传递给指针(左侧和右侧),以设置结构中的值。另一种方法是使用引用而不是指针。
以下是我为您提供的代码提出的修改:
void tree::build_tree(string &input, int i, node **n)
{
if(input[i] == '(')
{
string data; string temp;
//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);
// 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;
data = get_data(input, temp, i);
i = get_data_num(input, temp, i);
*n = new node;
(*n)->data = data;
(*n)->left = NULL;
(*n)->right = NULL;
if(input[i+1] == ' ')
{ i += 1; }
build_tree(input, i, &((*n)->left));
build_tree(input, i, &((*n)->right));
}
else if(input[i] == ' ')
{
i += 1;
}
else if(input[i] == ')')
{
*n = NULL;
}
else
{
cout << "The input tree is not in the correct format!" << endl;
}
}
然后是初次通话,
build_tree(的TestString,0,&安培;根);
由于未提供get_data和get_data_num,因此我无法测试所做的更改。