I have the following recursive method.
It evaluates a node (that represent a logical expression), using deep first search traversal :
EvaluateNode(Node node)
{
bool result;
switch(node.Type)
{
case AND_OPERATOR:
result = true;
foreach(Node nodeChild in node.Childrens)
{
childresult = EvaluateNode(nodeChild);
result = result && childresult;
}
case OR_OPERATOR:
result = false;
foreach(Node nodeChild in node.Childrens)
{
childresult = EvaluateNode(nodeChild);
result = result || childresult;
}
case VALUE:
result = node.Value;
}
return result;
}
I'd like to convert this to a stack/queue based, non recursive solution. Here is what I tried so far (incomplete) :
bool result;
stack.Push(node);
while(!stack.Empty())
{
Node node = stack.Pop();
switch(node.Type)
{
case AND_OPERATOR:
foreach(Node nodeChild in node.Childrens)
{
stack.Push(nodeChild);
}
case OR_OPERATOR:
foreach(Node nodeChild in node.Childrens)
{
stack.Push(nodeChild);
}
case VALUE:
result = node.Value;
}
}
My guess is that I would need another stack for storing results but I have not been able to figure this out.
Aucun commentaire:
Enregistrer un commentaire