我一直在處理來自文件的輸入,並認爲我的邏輯正確,但是我的節點沒有正確鏈接。我能夠正確設置根目錄,並且程序能夠遍歷字符串並正確加載節點,而不是鏈接它們。任何人都可以幫我理清我的邏輯並找出問題所在嗎? (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'應該是一個參考。否則,兩個連續的遞歸調用(左右解析子節點)將在同一位置讀取!只需在參數列表中嘗試「int&i」,不做其他更改,並報告結果。 – leemes 2013-02-09 14:11:25
@leemes我試過,我仍然得到相同的結果。 – user2057191 2013-02-09 14:48:06
請發佈您的節點結構。這可能有助於理解問題。 – Glenn 2013-02-09 15:45:21