1
我有一個簡單的狀態機(在下面輸入)。我的主要問題是我試圖對我的狀態機的函數進行遞歸調用。我在輸入函數時所做的是爲我的樹創建一個新節點,然後推送它。當我進行遞歸調用時,我一遍又一遍地創建一個新節點。這可以工作,但是當向父母添加孩子時,我有點困惑。有人可以幫助看看這個,並幫助我把我的樹節點(我假設的父母)和附加一個孩子嗎?C++遞歸樹與指針和狀態機構建
TreeNodeClass* ProcessTree(TokenT token, vector <list <stateAssoc> >& vecTree, int depth)
{
int state = 1; //Assume this is a new record.
bool noState = false;
bool update = true;
int dex = 0;
string root, value, data, tag;
TreeNodeClass* treeNode;
treeNode = new TreeNodeClass; //Assume a new node per state machine visit.
//Need 11 to break out of loop as well.
while(state != 10)
{
switch(state)
{
case 1: dex = 1;
break;
case 2: dex = 6;
root = yylval;
break;
case 3: dex = 7;
break;
case 4: dex = 3;
value = yylval;
treeNode->CreateAttrib(root, value);
break;
case 5: dex = 2;
break;
case 6: dex = 4;
data = yylval;
break;
case 7: //Really Don't do anything. Set the tag creation at 8...
dex = 8;
tag = yylval;
if(data != "" and data != "authors")
treeNode->CreateTag(data, tag);
break;
case 8: {
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode);
}
token = TokenT(yylex()); //Get a new token to process.
dex = 5;
break;
case 9: dex = 9;
update = false;
if(yylval != treeNode->ReturnTag())
{
state = 11;
}
break;
case 10: update = false;
treeNode->SetHeight(1);
break;
default: cout << "Error " << endl;
cout << state << endl;
cin.get();
break;
}
if(!noState)
state = FindMatch(vecTree[dex], token);
if(update)
token = TokenT(yylex());
else
update = true;
}
return treeNode;
}
你可能會認爲dex只是一個返回正確狀態或11(錯誤)的列表數組的索引。你也可以假設這個函數在輸入文件中至少被調用一次,並且已經開始解析。感謝您的幫助。在你的代碼