Build Binary Expression Tree From Infix Expression Problem
Description
LeetCode Problem 1597.
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 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, whose in-order traversal reproduces s after omitting the parenthesis from it.
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:

Input: s = "3*4-2*5"
Output: [-,*,*,3,4,2,5]
Explanation: The tree above is the only valid tree whose inorder traversal produces s.
Example 2:

Input: s = "2-3/(5*2)+1"
Output: [+,-,1,2,/,null,null,null,null,3,*,null,null,5,2]
Explanation: The inorder traversal of the tree above is 2-3/5*2+1 which is the same as s without the parenthesis. The tree also produces the correct result and its operands are in the same order as they appear in s.
The tree below is also a valid binary expression tree with the same inorder traversal as s, but it not a valid answer because it does not evaluate to the same value.

The third tree below is also not valid. Although it produces the same result and is equivalent to the above trees, its inorder traversal does not produce s and its operands are not in the same order as s.

Example 3:
Input: s = "1+2+3+4+5"
Output: [+,+,5,+,4,null,null,+,3,null,null,1,2]
Explanation: The tree [+,+,5,+,+,null,null,1,2,3,4] is also one of many other valid trees.
Constraints:
1 <= s.length <= 100sconsists of digits and the characters'(',')','+','-','*', and'/'.- Operands in
sare exactly 1 digit. - It is guaranteed that
sis a valid expression.
Solution
Approach: Two Stacks (Shunting Yard)
This is the classic way to evaluate an infix expression with two stacks, except that instead of computing numbers we build tree nodes:
nodesholds finished subtrees andopsholds operators and(that are still waiting for their right operand.- A digit becomes a leaf and is pushed onto
nodes. (is pushed ontoops.)builds nodes until the matching(is on top, then pops the(.- An operator
ofirst builds nodes while the top ofopsis an operator with precedence greater than or equal too(*and/are 2,+and-are 1), then pusheso.
"Building" pops two subtrees (the right one is on top) and one operator, and pushes a new node with that operator and the two subtrees as children. When the string ends, build the rest; the only node left is the root.
The "or equal" part matters: it makes operators of the same level group from left to right, so 1-2-3 becomes (1-2)-3 and not 1-(2-3), which would have a different value. Parentheses vanish from the tree because they only control when nodes are built, and operands keep their order because they are pushed in the order they appear.
Complexity: O(n) time and O(n) extra space.
# Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def expTree(self, s: str) -> 'Node':
prec = {"+": 1, "-": 1, "*": 2, "/": 2}
nodes = [] # finished subtrees
ops = [] # operators and "(" still waiting for their right operand
def build() -> None:
# join the two newest subtrees under the newest operator
right = nodes.pop()
left = nodes.pop()
nodes.append(Node(ops.pop(), left, right))
for c in s:
if c.isdigit():
nodes.append(Node(c))
elif c == "(":
ops.append(c)
elif c == ")":
while ops[-1] != "(":
build()
ops.pop()
else:
# earlier operators that bind at least as tightly are complete now
while ops and ops[-1] != "(" and prec[ops[-1]] >= prec[c]:
build()
ops.append(c)
while ops:
build()
return nodes[-1]