Created
December 15, 2019 20:57
-
-
Save Sukhrobjon/1301a097a7756cc4b2fd3c5ad933115e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def evaluate(self, node=None) -> float: | |
""" | |
Calculate this tree expression recursively | |
Args: | |
node(BinaryTreeNode): starts at the root node | |
""" | |
# initialize | |
if node is None: | |
node = self.root | |
# empty tree | |
if node is None: | |
return 0 | |
# check if we are at the leaf, it means it is a operand | |
if node.is_leaf(): | |
node.value = float(node.data) | |
val = float(node.data) | |
return val | |
left_value = self.evaluate(node.left) | |
right_value = self.evaluate(node.right) | |
# addition | |
if node.data == "+": | |
return left_value + right_value | |
# subtraction | |
elif node.data == "-": | |
print(f"node value: {node.value}") | |
return left_value - right_value | |
# division | |
elif node.data == "/": | |
return left_value / right_value | |
# multiplication | |
elif node.data == "*": | |
return left_value * right_value | |
# power | |
else: | |
return left_value ** right_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment