← zpět

Stromy

Co jsme dnes dělali

import sys


class BSTNode:
    def __init__(self, value, left=None, right=None, parent=None):
        self.value = value
        self.left = left
        self.right = right


class BST:
    def __init__(self, root=None):
        self.root = root

    @staticmethod
    def __from_sorted_list(values):
        if not values:
            return None
        mid = len(values) // 2
        root = BSTNode(values[mid])
        root.left = BST.__from_sorted_list(values[:mid])
        root.right = BST.__from_sorted_list(values[mid + 1 :])
        return root

    @staticmethod
    def from_sorted_list(values):
        return BST(BST.__from_sorted_list(values))

    def find(self, value):
        node = self.root
        while node is not None:
            if node.value == value:
                return node
            elif node.value < value:
                node = node.right
            else:
                node = node.left
        return None

    def print_tree(self):
        def _print_tree(node, depth):
            if node is None:
                return
            _print_tree(node.right, depth + 1)
            print("  " * depth + str(node.value))
            _print_tree(node.left, depth + 1)

        _print_tree(self.root, 0)

    def insert(self, value):
        # TODO: Implement insertion
        raise NotImplementedError

    def delete(self, value):
        # TODO: Implement deletion
        raise NotImplementedError

    def print_preorder(self):
        # TODO: Implement preorder traversal
        raise NotImplementedError

    def print_inorder(self):
        # TODO: Implement inorder traversal
        raise NotImplementedError


values = list(range(10))
print(values)
bst = BST.from_sorted_list(values)

if bst is None:
    print("BST is None")
    sys.exit(1)

bst.print_tree()