-
Notifications
You must be signed in to change notification settings - Fork 0
/
050.py
84 lines (61 loc) · 2.03 KB
/
050.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
"""
Problem:
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).
"""
from __future__ import annotations
from typing import Callable, Optional, Union
from DataStructures.Tree import BinaryTree, Node
# symbol to function map
OPERATIONS_DICT = {
"+": lambda num1, num2: num1 + num2,
"-": lambda num1, num2: num1 - num2,
"*": lambda num1, num2: num1 * num2,
"/": lambda num1, num2: num1 / num2,
}
class ExpressionTreeNode(Node):
def __init__(
self,
val: Union[int, float, str, Callable],
left: Optional[ExpressionTreeNode] = None,
right: Optional[ExpressionTreeNode] = None,
) -> None:
Node.__init__(self, val, left, right)
def transform_helper(self) -> None:
if self.val in OPERATIONS_DICT:
self.val = OPERATIONS_DICT[self.val]
self.left.transform_helper()
self.right.transform_helper()
def calculate_helper(self) -> Union[int, float]:
if callable(self.val):
return self.val(self.left.calculate_helper(), self.right.calculate_helper())
return self.val
def calculate_expression_tree(tree: BinaryTree) -> Union[int, float]:
root = tree.root
if root:
root.transform_helper()
return root.calculate_helper()
return None
if __name__ == "__main__":
tree = BinaryTree()
tree.root = ExpressionTreeNode("*")
tree.root.left = ExpressionTreeNode("+")
tree.root.right = ExpressionTreeNode("+")
tree.root.left.left = ExpressionTreeNode(3)
tree.root.left.right = ExpressionTreeNode(2)
tree.root.right.left = ExpressionTreeNode(4)
tree.root.right.right = ExpressionTreeNode(5)
print(calculate_expression_tree(tree))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(log(n))
"""