Assume that you are given an expression tree that contains only integer constant
ID: 3813961 • Letter: A
Question
Assume that you are given an expression tree that contains only integer constants and the binary operators '-', '+', '*' and '/'. Here's an example: The following is the expression tree node definition: public class ETNode {String data;//either integer constant or binary operator ETNode left, right; ...} (a) Complete the following method to evaluate an expression given a reference to the root of its expression tree. You may implement helper methods if you wish.//Evaluates an expression tree given its root returns 0 if tree is empty public static double evaluate (ETNode root) {(Things to know: The Integer.parseInt (String) method returns the int value represented by the string parameter. The Character. Is Digit (char) method returns true if the char parameter is a digit false otherwise.)Explanation / Answer
ETNode.java
public class ETNode
{
String data;
ETNode left, right;
ETNode(String x)
{
data = x;
left = null;
right = null;
}
// Recursive method to evaluate. It evaluate first left sub tree and then right subtree and then apply operation in node.
public static double evaluate(ETNode root)
{
// empty tree
if (root == null)
return 0;
// leaf node i.e, an integer
if ((root.left == null) && (root.right == null))
return Integer.parseInt(root.data);
// Evaluate left subtree
double l_val = evaluate(root.left);
// Evaluate right subtree
double r_val = evaluate(root.right);
// Check which operator to apply
if (root.data.equals("+"))
return l_val+r_val;
if (root.data.equals("-"))
return l_val-r_val;
if (root.data.equals("*"))
return l_val*r_val;
return l_val/r_val;
}
public static void main(String [] args)
{
ETNode root = new ETNode("+");
ETNode leftChild = new ETNode("2");
ETNode rightChild = new ETNode("*");
root.left = leftChild;
root.right = rightChild;
ETNode leftChildOfRightChild = new ETNode("4");
ETNode rightChildOfRightChild = new ETNode("55");
rightChild.left = leftChildOfRightChild;
rightChild.right = rightChildOfRightChild;
double expressionResults = evaluate(root);
System.out.println("Expression results for given tree: " + expressionResults);
}
}
As expression tree was not provided I made something static to demonstrate this works by adding a main method to the class.
Sample output
Expression results for given tree: 222.0
Please rate positively if this solved your question. Comment if something is not clear.