【问题标题】:How do I implement a binary expression tree in Java? [closed]如何在 Java 中实现二叉表达式树? [关闭]
【发布时间】:2017-03-16 18:35:11
【问题描述】:

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

【问题讨论】:

标签: java binary-tree expression-trees


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    相关资源
    最近更新 更多