如何在Java中实现二进制表达式树?

时间:2017-03-16 18:35:11

标签: java binary-tree expression-trees

我正在努力创建一个二元表达式树,并且还没有找到我在网上寻找的确切内容。

1 个答案:

答案 0 :(得分:1)

要实现它,请从包含自己子节点的结构开始。

public class Node {
  public Node left;
  public Node right;
  public String payload;

  Node(String payload){
    left = null;
    right = null;
    this.payload = payload;
  }

  Node(Node left, Node right, String payload){
    this.left = left;
    this.right = right;
    this.payload = payload;
  }
}

然后使用递归方法将结果返回给被调用的方法。

int total(Node point){
    if (point == null) return 0;
    switch (point.payload){
        case "+": return total(point.left) + total(point.right);
        case "-": return total(point.left) - total(point.right);
        case "/": return total(point.left) / total(point.right);
        case "*": return total(point.left) * total(point.right);
        default: return Integer.parseInt(point.payload);
    }
}