1

我有以下代码。我构建了一个表达式树,但我一直在解析它以找到结果

您将在我的代码中找到详细信息

public enum OpertaionType { add, sub, div, mul} 

public class Node {
    public Node(Node lhs, Node rhs, OpertaionType opType, int index) {
        this.lhs = lhs;
        this.rhs = rhs;
        this.opType = opType;
        this.index = index;
    }
    Node lhs;
    Node rhs;
    OpertaionType opType;
    int index;
}
class Program
{
    static void Main(string[] args)
    {
        // I don't want this to be part of the node data structure
        // because in the actual implementation I will end up referencing an
        // array of data

        int[] value = new int[5];

        Node[] nodes = new Node[value.Length];
        for (int i = 0; i < value.Length; i++)
        {
            value[i] = i+1;
            nodes[i] = new Node(null, null, 0, i);
        }



        // suppose I constructed the tree like that 
        // note that the end nodes are marked by non-negative index that indexes the
        // values array

        Node a = new Node(nodes[0], nodes[1], OpertaionType.add, -1);
        Node b = new Node(nodes[2], a, OpertaionType.mul, -1);
        Node c = new Node(b, nodes[3], OpertaionType.div, -1);

        // How can I find the result of Node c programatically
        // such that the result is (a[2]*(a[0]+a[1]))/a[3] = 9/4

    }
}
4

2 回答 2

3

您需要一个递归算法,传递值数组(代码未经测试):

class Node{
  //...
  double compute(int[] values){
    if(index >= 0)
      return values[index]; // leaf node; value stored in array
    switch(opType){
      case add: return lhs.compute(values)+rhs.compute(values);
      case sub: return lhs.compute(values)-rhs.compute(values);
      case div: return lhs.compute(values)*rhs.compute(values);
      case mul: return lhs.compute(values)/rhs.compute(values);
    }
    throw new Exception("unsupported operation type");
  }
}

请注意,这会以双精度执行所有计算;如果你真的想要 9/4,你需要使用一个有理类型。

于 2009-08-08T17:10:54.567 回答
1

有关 C# 3.0 自己的表达式树的简单基本介绍,请参见此处;不幸的是,我不知道有关该主题的真正广泛而深入的文本(也许是一本书..?)。

至于您自己的手卷格式,您可以通过递归进行最简单的评估;在伪代码中:

def valof(node):
  if node.index >= 0: 
    return whateverarray[node.index]
  L = valof(node.lhs)
  R = valof(node.rhs)
  if node.opType == add:
    return L + R
  if node.opType == mul:
    return L * R
  # etc etc

作为进一步的转折,当输入值是整数时,您似乎想要分数结果,请记住使用分数/有理数类型进行计算 - 不确定 C# 是否带有,但最坏的情况是您可以在网上找到很多;-)。

于 2009-08-08T17:05:34.097 回答