- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 44 lines of Python from the credited upstream file build-binary-expression-tree-from-infix-expression.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Node(object):6 def __init__(self, val=" ", left=None, right=None):7 self.val = val8 self.left = left9 self.right = right10 11 12class Solution(object):13 def expTree(self, s):14 """15 :type s: str16 :rtype: Node17 """18 def compute(operands, operators):19 right, left = operands.pop(), operands.pop()20 operands.append(Node(val=operators.pop(), left=left, right=right))21 22 precedence = {'+':0, '-':0, '*':1, '/':1}23 operands, operators, operand = [], [], 024 for i in xrange(len(s)):25 if s[i].isdigit():26 operand = operand*10 + int(s[i])27 if i == len(s)-1 or not s[i+1].isdigit():28 operands.append(Node(val=str(operand)))29 operand = 030 elif s[i] == '(':31 operators.append(s[i])32 elif s[i] == ')':33 while operators[-1] != '(':34 compute(operands, operators)35 operators.pop()36 elif s[i] in precedence:37 while operators and operators[-1] in precedence and \38 precedence[operators[-1]] >= precedence[s[i]]:39 compute(operands, operators)40 operators.append(s[i])41 while operators:42 compute(operands, operators)43 return operands[-1]44