Please read the comment ins code ExpressionTree.java ---------------------------------- /** * This is the class for Expression Tree. * Used to create Expression Tree and Evaluate it */ /** * Following logic is used to construct a Tree * Here we use stack for Preparing Tree * Loop through given Expression String * If Character is Operand , Create node and push to stack * If Character is Operator then * 1)Create Node for Operator * 2)Pop 2 nodes from Stack and Made * OpretorNode--> left == first node pop * OpretorNode--> right == second node pop * At the end of creation of Expression Tree, Stack have only one node , which is root of Expression tree */ /** Class ExpressionTree **/ class ExpressionTree { /** class TreeNode * Stored Character ==> Digit(0..9) or a Operator +,-,*,/ * Left Node and Right Node * * **/ class TreeNode { char data; TreeNode left, right; /** constructor **/ public TreeNode(char data) { this.data = data; this.left = null; this.right = null; } } /** class StackNode **/ class StackNode { TreeNode treeNode; StackNode next; /** constructor **/ public StackNode(TreeNode treeNode) { this.treeNode = treeNode; next = null; } } private static StackNode top; /** constructor * Constructor takes input string like \"+-+7*935*82*625\" * Input should be in Prefix notation * **/ public ExpressionTree(String expression) { top = null; //Call Method for prepare expression tree buildTree(expression); } /** function to clear tree **/ public void clear() { top = null; } /** function to push a node **/ private void push(TreeNode ptr) { if (top == null) top = new StackNode(ptr); else { StackNode nptr = new StackNode(ptr); nptr.next = top; top = nptr; } } /** function to pop a node * When it find operator pop 2 elements from Stack * * **/ private TreeNode pop() { if (top == null) throw new RuntimeException(\"Underflow\"); else { TreeNode ptr = top.treeNode; top = top.next; return ptr; } } /** function to get top node **/ private TreeNode peek() { return top.treeNode; } /** function to insert character **/ private void insert(char val) { try { //If Operand , Create node and push to Stack if (isDigit(val)) { TreeNode nptr = new TreeNode(val); push(nptr); } //If Operator , Create node and popup 2 elements and make them its right and left else if (isOperator(val)) { TreeNode nptr = new TreeNode(val); nptr.left = pop(); nptr.right = pop(); push(nptr); } } catch (Exception e) { System.out.println(\"Invalid Expression\"); } } /** function to check if digit **/ private boolean isDigit(char ch) { return ch >= \'0\' && ch <= \'9\'; } /** function to check if operator **/ private boolean isOperator(char ch) { return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\'; } /** function to convert character to digit **/ private int toDigit(char ch) { return ch - \'0\'; } /** function to build tree from input */ public void buildTree(String eqn) { for (int i = eqn.length() - 1; i >= 0; i--) insert(eqn.charAt(i)); } /** function to evaluate tree */ public dou.