publicclassTreeNode {
String val;
TreeNode left;
TreeNode right;
TreeNode(String x) {
val = x;
}
}
publicclassExpressionTreeEvaluator {
publicintevaluate(TreeNode root) {
// Base case: if the root is a leaf node (operand), return its integer valueif (root.left==null&& root.right==null) {
return Integer.parseInt(root.val);
}
// Recursively evaluate the left and right subtreesint left = evaluate(root.left);
int right = evaluate(root.right);
// Apply the operator at the root to the values from the left and right subtreesswitch (root.val) {
case"+":
return left + right;
case"-":
return left - right;
case"*":
return left * right;
case"/":
return left / right;
default:
thrownew IllegalArgumentException("Invalid operator: "+ root.val);
}
}
publicstaticvoidmain(String[] args) {
// Build the tree from the example TreeNode root =new TreeNode("+");
root.left=new TreeNode("*");
root.right=new TreeNode("/");
root.left.left=new TreeNode("-");
root.left.right=new TreeNode("100");
root.left.left.left=new TreeNode("5");
root.left.left.right=new TreeNode("4");
root.right.left=new TreeNode("100");
root.right.right=new TreeNode("20");
// Evaluate the expression tree ExpressionTreeEvaluator evaluator =new ExpressionTreeEvaluator();
int result = evaluator.evaluate(root);
// Output the result System.out.println("The result of the expression tree is: "+ result);
}
}