-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdailycoding050.py
69 lines (51 loc) · 1.33 KB
/
dailycoding050.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
"""
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).
solution:
Recurse on the tree. If the current node is an operator, then recursively evaluate
the operator on the left and right child of the current node. Otherwise if the
current node value is a numeric type, then return the value.
"""
class Node:
def __init__(self, val):
self.val = val
self.left = self.right = None
def eval_tree(root):
if root.val.isnumeric():
return int(root.val)
return eval(f"{eval_tree(root.left)} {root.val} {eval_tree(root.right)}")
def main():
a = Node('3')
b = Node('2')
c = Node('4')
d = Node('5')
d = Node('+')
d.left = a
d.right = b
e = Node('+')
e.left = c
e.right = d
f = Node('*')
f.left = e
f.right = d
tests = {
a: 3,
d: 5,
e: 9,
f: 45
}
if all(eval_tree(k) == tests[k] for k in tests):
print("Passed")
else:
print("Failed")
if __name__ == '__main__':
main()