forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-an-expression-tree-with-evaluate-function.py
96 lines (79 loc) · 2.37 KB
/
design-an-expression-tree-with-evaluate-function.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# Time: O(n)
# Space: O(h)
import abc
from abc import ABCMeta, abstractmethod
class Node:
__metaclass__ = ABCMeta
# define your fields here
@abstractmethod
def evaluate(self):
pass
import operator
class NodeIter(Node):
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def evaluate(self):
result = [0]
stk = [(1, (self, result))]
while stk:
step, args = stk.pop()
if step == 1:
node, ret = args
if node.val.isdigit():
ret[0] = int(node.val)
continue
ret1, ret2 = [0], [0]
stk.append((2, (node, ret1, ret2, ret)))
stk.append((1, (node.right, ret2)))
stk.append((1, (node.left, ret1)))
elif step == 2:
node, ret1, ret2, ret = args
ret[0] = NodeIter.ops[node.val](ret1[0], ret2[0])
return result[0]
class TreeBuilder(object):
def buildTree(self, postfix):
"""
:type s: List[str]
:rtype: int
"""
stk = []
for c in postfix:
if c.isdigit():
stk.append(NodeIter(c))
else:
node = NodeIter(c)
node.right = stk.pop()
node.left = stk.pop()
stk.append(node)
return stk.pop()
# Time: O(n)
# Space: O(h)
class NodeRecu(Node):
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def evaluate(self):
if self.val.isdigit():
return int(self.val)
return NodeRecu.ops[self.val](self.left.evaluate(), self.right.evaluate())
class TreeBuilder2(object):
def buildTree(self, postfix):
"""
:type s: List[str]
:rtype: int
"""
stk = []
for c in postfix:
if c.isdigit():
stk.append(NodeRecu(c))
else:
node = NodeRecu(c)
node.right = stk.pop()
node.left = stk.pop()
stk.append(node)
return stk.pop()