Here is my solution for the Daily Coding Challenge 50
Given an arithmetic expression in the form of a binary tree, write a function to evaluate it
Example
*
/ \
+ +
/ \ / \
3 2 4 5
Return >> 45
Is this the most efficient way to do this?
"""Build an operation tree and calculate the result"""
class Tree:
def __init__(self, value, left=None, right=None):
"""Initialise values"""
self.value = value
self.left = left
self.right = right
def determine_sum(self, total):
if self.left == None and self.right == None:
return int(self.value)
if self.value == "*":
total += self.left.determine_sum(total) * self.right.determine_sum(total)
if self.value == "+":
total += self.left.determine_sum(total) + self.right.determine_sum(total)
if self.value == "-":
total += self.left.determine_sum(total) - self.right.determine_sum(total)
if self.value == "/":
total += self.left.determine_sum(total) / self.right.determine_sum(total)
return total
if __name__ == "__main__": #
n = Tree("*")
n.left = Tree("+")
n.right = Tree("+")
n.left.right = Tree("+")
n.right.right = Tree("+")
n.left.left = Tree("3")
n.left.right.left = Tree("4")
n.left.right.right = Tree("5")
n.right.left = Tree("6")
n.right.right.left = Tree("7")
n.right.right.right = Tree("4")
sum = n.determine_sum(0)
print(sum)