How do I implement a binary expression tree in Java?

binary-tree expression-trees java

Question

I am struggling to create a binary expression tree, and haven't found exactly what I'm looking for online.

Accepted Answer

To implement it, start with a structure which contains its own children.

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;
  }
}

Then use a recursive method to return the result to the called method.

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);
    }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why