def clone(tree1):
    tree2 = LinkedBinaryTree()
    tree2._add_root(tree1._root._element)
    _clone(tree1, tree1.root(), tree2, tree2.root())
    return tree2


def _clone(tree1, t, tree2, p):
    if tree1.left(t) is not None:
        new_left = tree2._add_left(p, tree1.left(t)._node._element)
        _clone(tree1, tree1.left(t), tree2, new_left)

    if tree1.right(t) is not None:
        new_right = tree2._add_right(p, tree1.right(t)._node._element)
        _clone(tree1, tree1.right(t), tree2, new_right)


t = LinkedBinaryTree()
root = t._add_root(0)
a = t._add_left(root, 1)
b = t._add_right(root, 2)
c = t._add_left(a, 3)
d = t._add_right(a, 4)
# e = t._add_left(d, 5)

parenthesize(t, t.root())
new = clone(t)
print()
parenthesize(new, new.root())

class newBinaryEulerTour(BinaryEulerTour):
    def _hook_postvisit(self, p, d, path, results):

        if self._tree.is_leaf(p):
            print("node({}) balance is NaN".format(p._node._element))
            return 0
        else:
            l, r = results[0], results[1]
            print("node({}) balance is {}".format(p._node._element, r - l))
            return l + r + 1


t = LinkedBinaryTree()
root = t._add_root(0)
a = t._add_left(root, 1)
b = t._add_right(root, 2)
c = t._add_left(a, 3)
d = t._add_right(a, 4)
# e = t._add_left(d, 5)
"""
     0
  1     2
3  4
"""
parenthesize(t, t.root())
print()
new = newBinaryEulerTour(t)
print(new.execute())
"""
Give the output of the function parenthesize(T, T.root( )), as described
in Code Fragment 8.25, when T is the tree of Figure 8.8.

- ( / ( * ( + ( 3, 1), 3), + ( - ( 9, 5), 2)), + ( * ( 3, - ( 7, 4)), 6))
"""
from ExpressionTree import build_expression_tree
from other import parenthesize
x = build_expression_tree('(((3+1)*3)/((9-5)+2))-((3*(7-4))+6))')
print(x, '=', x.evaluate())
parenthesize(x, x.root())
Пример #4
0
        # swap them!
        tree._replace(greatest, tree._replace(p, greatest.element()))
        algorithm(tree, greatest)


"""
     .      
   .   .   
  0 1 9 3 
"""
# preparation part
tree = LinkedBinaryTree()
root = tree._add_root(NullNode('root'))
root_right = tree._add_right(root, NullNode('right'))
root_left = tree._add_left(root, NullNode('left'))

root_left_left = tree._add_left(root_left, 0)
root_left_right = tree._add_right(root_left, 1)

root_right_left = tree._add_left(root_right, 9)
root_right_right = tree._add_right(root_right, 3)

# preparation part end

print('Before:')
parenthesize(tree, tree.root())
algorithm(tree, root)
print('\nAfter:')
parenthesize(tree, tree.root())
#