1597. Build Binary Expression Tree From Infix Expression
Last updated
Last updated
https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression
A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with 2 children) correspond to the operators '+'
(addition), '-'
(subtraction), '*'
(multiplication), and '/'
(division).
For each internal node with operator o
, the infix expression that it represents is (A o B)
, where A
is the expression the left subtree represents and B
is the expression the right subtree represents.
You are given a string s
, an infix expression containing operands, the operators described above, and parentheses '('
and ')'
.
Return any valid binary expression tree, which its in-order traversal reproducess
after omitting the parenthesis from it (see examples below).
Please note that order of operations applies in s
. That is, expressions in parentheses are evaluated first, and multiplication and division happen before addition and subtraction.
Operands must also appear in the same order in both s
and the in-order traversal of the tree.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= s.length <= 1000
s
consists of digits and the characters '+'
, '-'
, '*'
, and '/'
.
Operands in s
are exactly 1 digit.
It is guaranteed that s
is a valid expression.