Given an expression tree, evaluate the arithmetic expression represented by the tree, and produce its fully parenthesised form. An expression tree is a binary tree in which:
Each leaf node contains an operand (integer).
Each internal (non-leaf) node contains an operator (+, -, *, or /).
In an expression tree, leaf nodes contain operands (e.g., integers), and internal nodes represent operators (e.g., +, -, *, /). Evaluation proceeds in a recursive post-order traversal (evaluate left and right subtrees first, and then apply the operator on the results).
Construct the parenthesised form by recursively combining the sub-expressions in the required format while traversing the tree.
classTreeNode:
def __init__(self, value, left=None, right=None):
self.val = value
self.left = left
self.right = right
classSolution:
defevaluateExpressionTree(self, root):
ifnot root:
return0, ""# If it's a leaf node, return the operand and its string form directlyifnot root.left andnot root.right:
return int(root.val), str(root.val)
# Recursively evaluate left and right children left_val, left_expr = self.evaluateExpressionTree(root.left)
right_val, right_expr = self.evaluateExpressionTree(root.right)
# Perform the operation based on current node's value operator = root.val
if operator =='+':
result = left_val + right_val
elif operator =='-':
result = left_val - right_val
elif operator =='*':
result = left_val * right_val
elif operator =='/':
result = left_val // right_val # Integer division parenthesised =f"({left_expr}{operator}{right_expr})"return result, parenthesised