def pre_order_expr(tree: BinaryTree): expr = '' if tree: expr = str(tree.getRootValue()) expr = expr + pre_order_expr(tree.getLeftChild()) expr = expr + pre_order_expr(tree.getRightChild()) return expr
def evaluate(tree: BinaryTree): operators = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } left, right = tree.getLeftChild(), tree.getRightChild() if left and right: fn = operators[tree.getRootValue()] return fn(evaluate(left), evaluate(right)) else: return tree.getRootValue()
def post_order_expr(tree: BinaryTree): expr = '' if tree: if tree.getLeftChild() and tree.getRightChild(): expr = '(' + post_order_expr(tree.getLeftChild()) expr = expr + post_order_expr(tree.getRightChild()) expr = expr + str(tree.getRootValue()) + ')' else: expr = post_order_expr(tree.getLeftChild()) expr = expr + post_order_expr(tree.getRightChild()) expr = expr + str(tree.getRootValue()) return expr
def build_parse_tree(expr: str) -> BinaryTree: expr, stack, bt = list(expr.replace(' ', '')), Stack(), BinaryTree('') stack.push(bt) tree = bt for i in expr: if i == '(': tree.insertLeft('') stack.push(tree) tree = tree.getLeftChild() elif i in '1234567890': tree.setRootValue(eval(i)) tree = stack.pop() elif i in '+-*/': tree.setRootValue(i) tree.insertRight('') stack.push(tree) tree = tree.getRightChild() elif i == ')': tree = stack.pop() else: raise ValueError('Unknown operator: ' + i) return bt
def setUp(self) -> None: self.bt = BinaryTree('a')
class TestBinaryTree(unittest.TestCase): def setUp(self) -> None: self.bt = BinaryTree('a') def testRootValue(self): self.assertEqual('a', self.bt.getRootValue()) def testGetLeftChild(self): self.assertEqual(None, self.bt.getLeftChild()) def testGetRightChild(self): self.assertEqual(None, self.bt.getRightChild()) def testBinaryTreeInsertLeftAndRight(self): self.bt.insertLeft('b') self.assertEqual('b', self.bt.getLeftChild().getRootValue()) self.bt.insertRight('c') self.assertEqual('c', self.bt.getRightChild().getRootValue()) self.bt.setRootValue('Hello World') self.assertEqual('Hello World', self.bt.getRootValue()) self.bt.getRightChild().setRootValue('PRC') self.assertEqual('PRC', self.bt.getRightChild().getRootValue()) self.bt.getLeftChild().insertLeft('d') self.assertEqual('d', self.bt.getLeftChild().getLeftChild().getRootValue())