Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive method called evaluateExpTree that takes a expression binary t

ID: 3575030 • Letter: W

Question

Write a recursive method called evaluateExpTree that takes a expression binary tree and evaluates it. An expression binary tree is a binary tree in which a node is either an operation or an operand. The data in each node of the tree is of type String.

evaluateExpTree method should have the following signature and should be included in a class called ExpressionTreeOperations.

public class ExpressionTreeOperations {

public double evaluateExpTree(BTNode<String> expTree) { /* your implementation*/ }

}

BTNode<String> represents a binary tree with data elements of typing String.

evaluateExpTree evaluates an expression tree using the following rules:

If the tree has only one node then the evaluation of the tree returns the double number equivalent of the node's String data.

If the tree has more than one node then first evaluate the left subtree, then evaluate the right subtree and then apply the operation in the root to the result of left and right subtrees. For the division operation, divide the result of the left subtree by the result of right subtree. The root contains one of the operations *,/,+ and -.

Explanation / Answer

public class ExpressionTreeOperations {

   public double evaluateExpTree(BTNode<String> expTree) {

    // the bode of the tree have the reference variables lefr, right, and data part called val.

if (expTree.left != null || expTree.right!=null) {
switch (expTree.val) {
case "+": return evaluateExpTree(expTree.left) + evaluateExpTree(expTree.right);
case "-": return evaluateExpTree(expTree.left) - evaluateExpTree(expTree.right);
case "*": return evaluateExpTree(expTree.left) * evaluateExpTree(expTree.right);
case "/": return evaluateExpTree(expTree.left) / evaluateExpTree(expTree.right);
}
} else {
return Double.parseDouble(expTree.val);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote