Skip to content

Commit a28651d

Browse files
authored
Create build-binary-expression-tree-from-infix-expression.py
1 parent 6d17ccc commit a28651d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Definition for a binary tree node.
5+
class Node(object):
6+
def __init__(self, val=" ", left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution(object):
13+
def expTree(self, s):
14+
"""
15+
:type s: str
16+
:rtype: Node
17+
"""
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 = [], [], 0
24+
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 = 0
30+
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]

0 commit comments

Comments
 (0)