File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node :
2
+ """Class to define tree nodes,
3
+ this has a value attribute to store the value, and
4
+ left and right attributes to point to the left and right child respectively"""
5
+ def __init__ (self , value ):
6
+ self .value = value
7
+ self .right = None
8
+ self .left = None
9
+
10
+ def expression_tree_evaluation (node ):
11
+ """A recursive function which evaluates the expression subtree passed to it
12
+ and returns the evaluated value"""
13
+ if node == None : # Node doesn't exist
14
+ return 0
15
+ if node .left == None and node .right == None : # leaf node containing an operand
16
+ return node .value
17
+
18
+ # node is an operator
19
+ left_child = expression_tree_evaluation (node .left )
20
+ right_child = expression_tree_evaluation (node .right )
21
+
22
+ return eval (str (left_child )+ node .value + str (right_child ))
23
+
24
+
25
+ # DRIVER CODE
26
+
27
+ if __name__ == '__main__' :
28
+ # Expression in the example : (5*4)+(100-2)
29
+ root = Node ('+' )
30
+ root .left = Node ('*' )
31
+ root .left .left = Node ('5' )
32
+ root .left .right = Node ('4' )
33
+ root .right = Node ('-' )
34
+ root .right .left = Node ('100' )
35
+ root .right .right = Node ('20' )
36
+ print (expression_tree_evaluation (root ))
You can’t perform that action at this time.
0 commit comments