-
Notifications
You must be signed in to change notification settings - Fork 1
/
Microsoft_ArthimeticExpression.py
101 lines (56 loc) · 1.12 KB
/
Microsoft_ArthimeticExpression.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
'''
This problem was asked by Microsoft.
Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer
and each internal node is one of '+', '−', '∗', or '/'.
Given the root to such a tree, write a function to evaluate it.
For example, given the following tree:
*
/ \
+ +
/ \ / \
3 2 4 5
You should return 45, as it is (3 + 2) * (4 + 5).
[*, +, 3, 2, +, 4, 5]
[3, +, 2, *, 4, +, 5]
'''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def evaluate(root):
operations = {
'-': lambda x, y: x - y,
'+': lambda x, y: x + y,
'/': lambda x, y: x / y,
'*': lambda x, y: x * y
}
def helper(root):
if type(root.val) == int:
return root.val
else:
left = helper(root.left)
right = helper(root.right)
return operations[root.val](left, right)
return helper(root)
'''
*
/ \
+ +
/ \ / \
3 2 4 5
'''
a = Node('*')
b = Node('+')
c = Node('+')
d = Node(3)
e = Node(2)
f = Node(4)
g = Node(5)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
print(evaluate(a))