forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
build-binary-expression-tree-from-infix-expression.py
43 lines (39 loc) · 1.42 KB
/
build-binary-expression-tree-from-infix-expression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Time: O(n)
# Space: O(n)
# 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(object):
def expTree(self, s):
"""
:type s: str
:rtype: Node
"""
def compute(operands, operators):
right, left = operands.pop(), operands.pop()
operands.append(Node(val=operators.pop(), left=left, right=right))
precedence = {'+':0, '-':0, '*':1, '/':1}
operands, operators, operand = [], [], 0
for i in xrange(len(s)):
if s[i].isdigit():
operand = operand*10 + int(s[i])
if i == len(s)-1 or not s[i+1].isdigit():
operands.append(Node(val=str(operand)))
operand = 0
elif s[i] == '(':
operators.append(s[i])
elif s[i] == ')':
while operators[-1] != '(':
compute(operands, operators)
operators.pop()
elif s[i] in precedence:
while operators and operators[-1] in precedence and \
precedence[operators[-1]] >= precedence[s[i]]:
compute(operands, operators)
operators.append(s[i])
while operators:
compute(operands, operators)
return operands[-1]