Skip to content

Commit 4c74e72

Browse files
authored
Merge pull request #464 from pushpit-J19/expression_tree
expression_tree_evaluation in python
2 parents dff31cb + c3bb96f commit 4c74e72

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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))

0 commit comments

Comments
 (0)