Skip to content

Commit fad76ca

Browse files
authored
Create design-an-expression-tree-with-evaluate-function.py
1 parent 0fc84b8 commit fad76ca

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
import abc
5+
from abc import ABCMeta, abstractmethod
6+
7+
8+
class Node:
9+
__metaclass__ = ABCMeta
10+
# define your fields here
11+
@abstractmethod
12+
def evaluate(self):
13+
pass
14+
15+
16+
import operator
17+
18+
19+
class NodeIter(Node):
20+
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
21+
22+
def __init__(self, val):
23+
self.val = val
24+
self.left = None
25+
self.right = None
26+
27+
def evaluate(self):
28+
result = [0]
29+
stk = [(1, (self, result))]
30+
while stk:
31+
step, args = stk.pop()
32+
if step == 1:
33+
node, ret = args
34+
if node.val.isdigit():
35+
ret[0] = int(node.val)
36+
continue
37+
ret1, ret2 = [0], [0]
38+
stk.append((2, (node, ret1, ret2, ret)))
39+
stk.append((1, (node.right, ret2)))
40+
stk.append((1, (node.left, ret1)))
41+
elif step == 2:
42+
node, ret1, ret2, ret = args
43+
ret[0] = NodeIter.ops[node.val](ret1[0], ret2[0])
44+
return result[0]
45+
46+
47+
class TreeBuilder(object):
48+
def buildTree(self, postfix):
49+
"""
50+
:type s: List[str]
51+
:rtype: int
52+
"""
53+
stk = []
54+
for c in postfix:
55+
if c.isdigit():
56+
stk.append(NodeIter(c))
57+
else:
58+
node = NodeIter(c)
59+
node.right = stk.pop()
60+
node.left = stk.pop()
61+
stk.append(node)
62+
return stk.pop()
63+
64+
65+
# Time: O(n)
66+
# Space: O(h)
67+
class NodeRecu(Node):
68+
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
69+
70+
def __init__(self, val):
71+
self.val = val
72+
self.left = None
73+
self.right = None
74+
75+
def evaluate(self):
76+
if self.val.isdigit():
77+
return int(self.val)
78+
return NodeRecu.ops[self.val](self.left.evaluate(), self.right.evaluate())
79+
80+
81+
class TreeBuilder2(object):
82+
def buildTree(self, postfix):
83+
"""
84+
:type s: List[str]
85+
:rtype: int
86+
"""
87+
stk = []
88+
for c in postfix:
89+
if c.isdigit():
90+
stk.append(NodeRecu(c))
91+
else:
92+
node = NodeRecu(c)
93+
node.right = stk.pop()
94+
node.left = stk.pop()
95+
stk.append(node)
96+
return stk.pop()

0 commit comments

Comments
 (0)