【发布时间】:2013-01-25 04:29:40
【问题描述】:
我一直在处理来自文件的输入,并认为我的逻辑是正确的,但我的节点没有正确链接。我能够正确设置根并且程序能够遍历字符串并正确加载节点,只是不链接它们。谁能帮我梳理一下我的逻辑并找出问题所在?
输入字符串为(A(B(DG)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应该是一个参考。否则,两个连续的递归调用(解析左右子节点)将在同一个位置读取!只需在参数列表中尝试int &i,无需其他更改,然后报告结果。 -
@leemes 我试过了,结果还是一样。
-
请发布您的节点结构。它可能有助于理解问题。
-
@Glenn 好的,我已经发布了。
-
@user2057191 谢谢。那非常有帮助。我在下面提供了一个答案,因为它不适合发表评论。
标签: c++ recursion file-upload tree binary-tree