Simplify a Binary Expression Tree
Problem statement
A valid binary expression tree is serialized in prefix order. Each token is +, -, *, a variable name, or a signed integer.
Simplify the tree bottom-up. Fold an operator when both children are integers. Also apply x + 0 = x, 0 + x = x, x - 0 = x, x * 1 = x, 1 * x = x, and x * 0 = 0. Return the simplified tree as one space-separated prefix expression.
Function
simplifyExpressionTree(preorder: String[]) → StringExamples
Example 1
preorder = ["+","*","x","1","0"]return = "x"Multiplication by one and addition of zero both disappear.
Example 2
preorder = ["*","+","2","3","y"]return = "* 5 y"The constant addition folds while the variable multiplication remains.
Constraints
1 <= preorder.length <= 10000.- The prefix sequence is a valid binary expression tree.
- Every folded result fits in a signed 64-bit integer.