def inorder_traversal(tree: BinaryTree): expression = "" if tree: leftchild = tree.get_left_child() if leftchild: expression += '( ' + inorder_traversal(leftchild) if str(tree.get_root_val()): expression += str(tree.get_root_val()) + ' ' rightchild = tree.get_right_child() if rightchild: expression += inorder_traversal(tree.get_right_child()) + ') ' return expression
def evaluate(parse_tree: BinaryTree): opers = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } left_c = parse_tree.get_left_child() right_c = parse_tree.get_right_child() if left_c and right_c: fn = opers[parse_tree.get_root_val()] return fn(evaluate(left_c), evaluate(right_c)) else: return parse_tree.get_root_val()
def evaluate_tree(tree: BinaryTree): token = tree.get_root_val() left_tree = tree.get_left_child() right_tree = tree.get_right_child() if token == 'not': opt = operator_dict.get(token, None) return opt(evaluate_tree(right_tree)) elif token in ['+', '-', '*', '/', 'and', 'or']: opt = operator_dict.get(token, None) return opt(evaluate_tree(left_tree), evaluate_tree(right_tree)) else: return token