0

I'm trying to do a expression tree from a infix string with recursive approach but when Parser threw an nullpointerexception but idk why, so if someone can help me, i will thank u.

Every operator with its operand will be enclosed in parentheses and every number will be surrounded by parentheses

Algorithm
Input: expression string
output: root of expression subtree for string

 1. node = new treeNode
 2. if string is a number
 3.   node.value = number extracted
 4.   return node
 5. endif
 6. node.op = extract operator
 7. node.left = parse (substring of string to the left of op)
 7. node.right = parse (substring of string to the right of op)


/**
 * ExpressionTree class
 */
public class ExpressionTree {
    private static class Node {
        int value;
        int op;
        Node left, right;
        boolean isNumber;
    }

    Node root;

    /**
     * Start parsing the equation
     * @param str equation
     */
    public void parsing(String str){
        root = parse(str);
    }
    /**
     * Empty constructor
     */
    ExpressionTree(){

    }
    Node parse(String str){
        Node node = new Node();
        try{
            int n = findRight(str,1);
            String left = str.substring(1,n+1);
            if (n == str.length()-1){
                String op = str.substring(1,str.length()-1);
                node.isNumber = true;
                node.value = getValue(op);
                System.out.println(" Returned Node" + " value " + node.value);
                return node;
            }
            int n2 = findLeft(str, str.length()-2);
            String right = str.substring(n2, str.length()-1);
            node.left = parse(left);
            node.right = parse(right);
            node.op = str.charAt(n+1);
            return node;
        }catch (IndexOutOfBoundsException | NullPointerException exception){
            System.out.println("Error parse : " + exception.getCause().toString());
            return null;
        }
    }

    /**
     * Find the matching left parent
     * @param str equation
     * @param pos index to start searching
     * @return position of left parent
     */
    public int findLeft(String str, int pos) {
        Stack<Character> stack = new Stack<>();
        try {
            stack.push(str.charAt(pos));
            for (int i = pos + 1; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c == '(')
                    stack.push(c);
                else if (c == ')') {
                    stack.pop();
                    if (stack.isEmpty()) {
                        System.out.println("Left i " + i);
                        return i;
                    }
                }
            }
        }catch (IndexOutOfBoundsException | NullPointerException exception) {
            System.out.println("ERROR findLeft: str " + str + " right = " + pos);
            System.out.println("Error :" + exception.getCause().toString());
        }
        return -1;
    }

    /**
     * Converts String operand to his value
     * @param op string operand
     * @return value of operand
     */
    public int getValue(String op) {
        try{
            return Integer.parseInt(op);
        }catch(NumberFormatException e){
            return -1;
        }
    }

    /**
     * Find the matching right parent
     * @param str equation
     * @param pos index to start searching
     * @return position of right parent
     */
    public int findRight(String str, int pos) {
        Stack<Character> stack = new Stack<>();
        stack.push(str.charAt(pos));
        //System.out.println("findRight: str "+ str + " left = "+ pos);
        try {
            for (int i = pos+1; i < str.length(); i++){
                char c = str.charAt(i);
                if(c == '(')
                    stack.push(c);
                else if (c == ')'){
                    stack.pop();
                    if (stack.isEmpty()){
                        System.out.println("Right i " + i);
                        return i;
                    }
                }
            }
        }catch (IndexOutOfBoundsException | NullPointerException exception) {
            System.out.println("ERROR findRight: str "+ str + " left = "+ pos);
            System.out.println("Error findRight : " + exception.getCause().toString());
        }
        return -1;
    }

    /**
     * Start solving
     * @return solved expression tree
     */
    public int computeValue(){
        return compute(root);
    }

    /**
     * Solve the expression tree recursively
     * @param node node
     * @return value of expression tree
     */
    public int compute(@org.jetbrains.annotations.NotNull Node node){
        if (node.isNumber){
            return node.value;
        }
        int left = compute(node.left);
        int right = compute(node.right);
        if (node.op == '+'){
            return left + right;
        }else if (node.op == '-'){
            return left - right;
        }else if (node.op == '*'){
            return left * right;
        }else if (node.op == '^'){
            return (int)Math.pow(left, right);//Temporal cast
        }else{
            return left / right;
        }
    }    
}

Main Class

public class App 
{
    public static void main( String[] args )
    {
        String str;
        str = "((((35)-((3)*((3)+(2))))/4))";
        ExpressionTree expressionTree = new ExpressionTree();
        expressionTree.parsing(str);
        int v = expressionTree.computeValue();
        System.out.println(str + " = " + v);
    }
}

When I run i get:

Returned Node value 35 and NullPointerException

2
  • 1
    The algorithm you’ve shown is incomplete and/or pretty useless. Where does it start? Usually when your input is a sequence you start at the left in that sequence, but your algorithm starts somewhere else and then expands both left and right. That’s certainly possible but it requires substantial preprocessing which renders this particular algorithm essentially redundant. Commented May 11, 2021 at 10:51
  • updated. Looks inside the string and finds the left and right substrings (on either side of the operator). Maybe useless? Idk, i was trying this aproacch but if I don't found solution I can do infix to postifx or prefix and then make the expression tree Commented May 11, 2021 at 10:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.