예제 #1
0
def serialize(node, arr):
    """ Serialization of binary tree. """
    if node is None:
        arr.append(None)
        return None
    arr.append(node.data)
    serialize(node.left, arr)
    serialize(node.right, arr)
    return arr


def deserialize(arr, i):
    """Deserialize the binary tree"""
    if arr[i[0]] is None:
        i[0] = i[0] + 1
        return None
    node = Node(arr[i[0]])
    i[0] = i[0] + 1
    node.left = deserialize(arr, i)
    node.right = deserialize(arr, i)
    return node


if __name__ == '__main__':

    arr = serialize(create_static_tree(), [])
    print(arr)
    node = deserialize(arr, [0])
    pre_order_traversal(node)
from trees.utils import Node, pre_order_traversal


def sum_tree(node):
    """ Convert the given binary tree into sum tree"""
    if node is None:
        return 0

    left_sum = sum_tree(node.left)
    right_sum = sum_tree(node.right)
    previous = node.data
    node.data = left_sum + right_sum

    return node.data + previous


if __name__ == '__main__':
    root = Node(10)
    root.left = Node(-2)
    root.right = Node(6)
    root.left.left = Node(8)
    root.left.right = Node(-4)
    root.right.left = Node(7)
    root.right.right = Node(5)
    sum_tree(root)
    pre_order_traversal(root)
def bt_from_linked_list(node, queue):
    """ Binary tree from linked list """
    root = Node(node.data)
    queue.append(root)
    while len(queue) > 0:
        pop_node = queue.pop(0)

        if node.right is not None:
            temp_node = Node(node.right.data)
            pop_node.left = temp_node
            queue.append(temp_node)
            node = node.right

        if node.right is not None:
            temp_node = Node(node.right.data)
            pop_node.right = temp_node
            queue.append(temp_node)
            node = node.right
    return root


if __name__ == '__main__':
    node = LinkedList(10)
    node.right = LinkedList(12)
    node.right.right = LinkedList(15)
    node.right.right.right = LinkedList(25)
    node.right.right.right.right = LinkedList(30)
    node.right.right.right.right.right = LinkedList(36)
    pre_order_traversal(bt_from_linked_list(node, []))