Search code examples
javabinary-treeexpression-trees

How do I implement a binary expression tree in Java?


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


Solution

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