コード例 #1
0
ファイル: linkedbst.py プロジェクト: Vihtoriaaa/bst
    def add(self, item):
        """Adds item to the tree."""
        # Tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)
        # Otherwise, search for the item's spot
        else:
            node = self._root

            while True:
                # New item is less, go left until spot is found
                if item < node.data:
                    if node.left is None:
                        node.left = BSTNode(item)
                        break
                    else:
                        node = node.left
                # New item is greater or equal,
                # go right until spot is found
                elif node.right is None:
                    node.right = BSTNode(item)
                    break
                else:
                    node = node.right
                    # End of recurse
        self._size += 1
コード例 #2
0
ファイル: linkedbst.py プロジェクト: ovsartem/trees
    def add(self, item):
        """Adds item to the tree."""
        node = self._root
        # Helper function to search for item's position

        # Tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)
        # Otherwise, search for the item's spot
        else:
            while node != None:
                if item < node.data:
                    if node.left == None:
                        node.left = BSTNode(item)
                        break
                    else:
                        node = node.left
                # New item is greater or equal,
                # go right until spot is found
                elif node.right == None:
                    node.right = BSTNode(item)
                    break
                else:
                    node = node.right
        self._size += 1
コード例 #3
0
    def add(self, value):
        """
        Adds value to the tree.
        """

        if self.isEmpty():
            self._root = BSTNode(value)
            self._size += 1
            return

        curr_node = self._root
        while True:
            if value < curr_node.data:
                if curr_node.left is None:
                    curr_node.left = BSTNode(value)
                    self._size += 1
                    break
                else:
                    curr_node = curr_node.left

            else:
                if curr_node.right is None:
                    curr_node.right = BSTNode(value)
                    self._size += 1
                    break
                else:
                    curr_node = curr_node.right
コード例 #4
0
ファイル: linkedbst.py プロジェクト: Tsalyk/test_linkedBST
    def add(self, item):
        """Adds item to the tree."""

        curr = self._root
        parent = None

        if curr is None:
            self._root = BSTNode(item)
            self._size += 1
            return

        while curr:
            parent = curr

            if item < curr.data:
                curr = curr.left
            else:
                curr = curr.right

        if item < parent.data:
            parent.left = BSTNode(item)
        else:
            parent.right = BSTNode(item)

        self._size += 1
コード例 #5
0
 def replace_ordered_list(self, llist):
     """Replace elements in BST with already ordered list"""
     self._size = 0
     self._root = BSTNode(llist[0])
     current_node = self._root
     for idx in range(1, len(llist)):
         current_node.right = BSTNode(llist[idx])
         current_node = current_node.right
コード例 #6
0
 def recurse(data, low, high):
     if low > high:
         return
     else:
         mid = low + (high - low) // 2
         node = BSTNode(data[mid])
         node.left = recurse(data, low, mid - 1)
         node.right = recurse(data, mid + 1, high)
         return node
コード例 #7
0
ファイル: linkedbst.py プロジェクト: misha2956/lab13_z12
 def get_node_recursive(leftp, rightp):
     if (rightp - leftp) == 1:
         return BSTNode(sorted_list[leftp])
     if (rightp - leftp) == 0:
         return None
     middle = int((leftp + rightp) / 2)
     node = BSTNode(sorted_list[middle])
     node.left = get_node_recursive(leftp, middle)
     node.right = get_node_recursive(middle + 1, rightp)
     return node
コード例 #8
0
 def make_bst(array):
     if not array:
         return None
     mid = len(array) // 2
     root = BSTNode(array[mid])
     if mid == 0:
         return root
     root.left = make_bst(array[:mid])
     root.right = make_bst(array[mid + 1:])
     return root
コード例 #9
0
        def recursive(nodes):
            middle_node = math.floor(((len(nodes) - 1) / 2))
            new_root = BSTNode(nodes[middle_node])
            if middle_node == 0:
                return new_root

            new_root.right = recursive(nodes[middle_node:])
            new_root.left = recursive(nodes[:middle_node])

            return new_root
コード例 #10
0
ファイル: linkedbst.py プロジェクト: TechInTech/dataStructure
 def recurse(node):
     if item < node.data:
         if node.left == None:
             node.left = BSTNode(item)
         else:
             recurse(node.left)
     elif node.right == None:
         node.right = BSTNode(item)
     else:
         recurse(node.right)
コード例 #11
0
ファイル: linkedbst.py プロジェクト: Sofiia2001/TicTacToe_BST
        def create_balanced_BST(arr):
            if len(arr) == 0:
                return None

            middle = len(arr) // 2

            new_root = BSTNode(data=arr[middle])
            new_root.left = create_balanced_BST(arr[:middle])
            new_root.right = create_balanced_BST(arr[middle + 1:])

            return new_root
コード例 #12
0
ファイル: linkedbst.py プロジェクト: sininni/BST_search
 def recurse(node):
     """
     Helper function to search for item's position.
     """
     if item < node.data:
         if node.left == None:
             node.left = BSTNode(item)
         else:
             recurse(node.left)
     elif node.right == None:
         node.right = BSTNode(item)
     else:
         recurse(node.right)
コード例 #13
0
    def making_tree(self):
        node = BSTNode(self._field)
        field1 = copy(self._field)
        field2 = copy(self._field)
        if self.status() == NOTHING:
            cell = choice(Board.possible_cells(self._field))
            cell2 = choice(Board.possible_cells(self._field))
            field1.turn(cell)
            field2.turn(cell2)
            node.left = self.making_tree(field1)
            node.right = self..making_tree(field2)

            return node
コード例 #14
0
 def recurse(node):
     # New item is less, go left until spot is found
     if item < node.data:
         if node.left == None:
             node.left = BSTNode(item)
         else:
             recurse(node.left)
     # New item is greater or equal,
     # go right until spot is found
     elif node.right == None:
         node.right = BSTNode(item)
     else:
         recurse(node.right)
コード例 #15
0
        def process(node):
            board = node.data
            if not board or not board.is_free_cell():
                return

            if board.check_status() is not None:
                return
            list2 = [[1, 0], [1, 2], [0, 1], [2, 1]]
            list1 = [[2, 2], [0, 0], [0, 2], [2, 0], [1, 1]]
            retries = 0
            while True:

                retries += 1

                if retries > 10:
                    list2 = list1
                position = random.choice(list2)
                if not board._board[position[0]][position[1]]:
                    break
            retries = 0
            new_board = copy.deepcopy(board)
            new_board.put([position[0], position[1]],
                          self.rec_cur_player[1])
            self.rec_cur_player = [
                self.rec_cur_player[1], self.rec_cur_player[0]]
            node.left = BSTNode(new_board)

            board = node.data
            if not board or not board.is_free_cell():
                return

            if board.check_status() is not None:
                return

            while True:
                retries += 1

                if retries > 10:
                    list1 = list2
                position = random.choice(list1)
                if not board._board[position[0]][position[1]]:

                    break

            new_board = copy.deepcopy(board)
            new_board.put([position[0], position[1]],
                          self.COMPUTER_MARK)
            node.right = BSTNode(new_board)

            process(node.left)
            process(node.right)
コード例 #16
0
ファイル: linkedbst.py プロジェクト: yankur/lab14
 def recurse(items):
     if not items:
         return None
     mid = len(items) // 2
     return BSTNode(items[mid],
                    left=recurse(items[:mid]),
                    right=recurse(items[mid + 1:]))
コード例 #17
0
    def add(self, item):
        """Adds item to the tree."""

        # Helper function to search for item's position
        def recurse(node):
            # New item is less, go left until spot is found
            if item < node.data:
                if node.left == None:
                    node.left = BSTNode(item)
                else:
                    recurse(node.left)
            # New item is greater or equal,
            # go right until spot is found
            elif node.right == None:
                node.right = BSTNode(item)
            else:
                recurse(node.right)
                # End of recurse

        # Tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)
        # Otherwise, search for the item's spot
        else:
            recurse(self._root)
        self._size += 1
コード例 #18
0
        def recursive(node, lst):
            mid = len(lst) // 2
            left = lst[:mid]
            right = lst[mid + 1:]
            # print('LEFT', left)

            if left != []:
                node.left = BSTNode(left[len(left) // 2])
                recursive(node.left, left)

            if right != []:
                node.right = BSTNode(right[len(right) // 2])
                recursive(node.right, right)

            else:
                return node
コード例 #19
0
    def rebalance(self):
        '''
        Rebalances the tree.
        :return:
        '''
        lst = list(self.inorder())
        self.clear()

        def recursive(node, lst):
            mid = len(lst) // 2
            left = lst[:mid]
            right = lst[mid + 1:]
            # print('LEFT', left)

            if left != []:
                node.left = BSTNode(left[len(left) // 2])
                recursive(node.left, left)

            if right != []:
                node.right = BSTNode(right[len(right) // 2])
                recursive(node.right, right)

            else:
                return node

        self._root = BSTNode(lst[len(lst) // 2])
        recursive(self._root, lst)
コード例 #20
0
        def recurse(lyst):

            if not lyst:
                return None

            mid = len(lyst) // 2

            return BSTNode(lyst[mid], left=recurse(lyst[:mid]), right=recurse(lyst[mid+1:]))
コード例 #21
0
ファイル: linkedbst.py プロジェクト: misha2956/lab13_z12
    def add(self, item):
        """Adds item to the tree."""

        if (self._leftmost_node is not None
                and item < self._leftmost_node.data):
            self._leftmost_node.left = BSTNode(item)
            self._leftmost_node = self._leftmost_node.left
            return

        if (self._rightmost_node is not None
                and item > self._rightmost_node.data):
            self._rightmost_node.right = BSTNode(item)
            self._rightmost_node = self._rightmost_node.right
            return

        # Tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)
        # Otherwise, search for the item's spot
        else:
            node = self._root
            while True:
                # New item is less, go left until spot is found
                if item < node.data:
                    if node.left == None:
                        node.left = BSTNode(item)
                        if (self._leftmost_node is None
                                or node.right.data < self._leftmost_node.data):
                            self._leftmost_node = node.left
                        break
                    else:
                        node = node.left
                        continue
                # New item is greater or equal,
                # go right until spot is found
                elif node.right == None:
                    node.right = BSTNode(item)
                    if (self._rightmost_node is None
                            or node.right.data > self._rightmost_node.data):
                        self._rightmost_node = node.right
                    break
                else:
                    node = node.right

        self._size += 1
コード例 #22
0
 def custom_add(self, elements):
     """
     Adds to the empty tree the list of elements.
     :param elements: list
     :rerurn: None
     """
     self.clear()
     self._root = BSTNode(elements[0])
     elements.pop(0)
     ptr = self._root
     for element in elements:
         if element.lower() < ptr.data.lower():
             ptr.left = BSTNode(element)
             ptr = ptr.left
         else:
             ptr.right = BSTNode(element)
             ptr = ptr.right
         self._size += 1
コード例 #23
0
        def recurse(node):
            # New item is less; go left until spot is found
            if item < node.data:
                if node.left == None:
                    node.left = BSTNode(item)
                else:
                    recurse(node.left)
            # New item is greater or equal;
            # go right until spot is found
            elif node.right == None:
                node.right = BSTNode(item)
            else:
                recurse(node.right)

            # Tree is empty, so new item goes at the root
            if self.is_empty():
                self.root = BSTNode(item)
            else:
                recurse(self.root)
            self.size += 1
コード例 #24
0
    def add(self, item):
        """Adds item to the tree."""

        # Tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)
        # Otherwise, search for the item's spot
        else:
            parent = None
            curr = self._root
            while curr is not None:
                parent = curr
                if item < curr.data:
                    curr = curr.left
                else:
                    curr = curr.right
            if item < parent.data:
                parent.left = BSTNode(item)
            else:
                parent.right = BSTNode(item)
        self._size += 1
コード例 #25
0
    def add(self, item):
        """Adds item to the tree."""

        # Tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)

        # Otherwise, search for the item's spot
        else:
            current = self._root
            while True:
                if item < current.data:
                    if current.left is not None:
                        current = current.left
                    else:
                        current.left = BSTNode(item)
                        break
                else:
                    if current.right is not None:
                        current = current.right
                    else:
                        current.right = BSTNode(item)
                        break
        self._size += 1
コード例 #26
0
    def add(self, item):
        """Adds item to the tree."""

        curr_node = self._root
        parent = None

        if self._root is None:
            self._root = BSTNode(item)

        else:
            while curr_node is not None:
                parent = curr_node
                if item < curr_node.data:
                    curr_node = curr_node.left
                else:
                    curr_node = curr_node.right

            if item < parent.data:
                parent.left = BSTNode(item)

            else:
                parent.right = BSTNode(item)

        self._size += 1
コード例 #27
0
ファイル: linkedbst.py プロジェクト: KernelBK/Files_01_xuef
    def add(self, item):
        newNode = BSTNode(item)
        def add_helper(node):
            if self.root is None:
                self.root = newNode
                return
            if item<node.data:
                if node.left is None:
                    node.left = newNode
                else:
                    add_helper(node.left)
            else:
                if node.right is None:
                    node.right = newNode
                else:
                    add_helper(node.right)

        add_helper(self.root)
        self.size += 1  
コード例 #28
0
ファイル: linkedbst.py プロジェクト: TechInTech/dataStructure
    def add(self, item):
        """在二叉搜索树中插入一项"""
        def recurse(node):
            if item < node.data:
                if node.left == None:
                    node.left = BSTNode(item)
                else:
                    recurse(node.left)
            elif node.right == None:
                node.right = BSTNode(item)
            else:
                recurse(node.right)

        # If tree is empty, so new item goes at the root
        if self.isEmpty():
            self._root = BSTNode(item)
        else:
            recurse(self._root)
        self._size += 1
コード例 #29
0
    def add(self, item):
        """增加item 到对应的位置"""
        def recurse(node):
            # item < node.data
            if item < node.data:
                if node.left == None:
                    node.left = BSTNode(item)
                else:
                    recurse(node.left)
            # item >= node.data
            elif node.right == None:
                node.right = BSTNode(item)
            else:
                recurse(node.right)

        if self.isEmpty():
            self._root = BSTNode(item)
        else:
            recurse(self._root)
        self._size += 1
コード例 #30
0
 def predecessor(self, item):
     """
     Returns the largest item that is smaller than
     item, or None if there is no such item.
     :param item:
     :type item:
     :return:
     :rtype:
     """
     pred = BSTNode(None)
     node = self._root
     while node:
         if item > node.data:
             pred = node
             node = node.right
         elif item < node.data:
             node = node.left
         else:
             break
     return pred.data
コード例 #31
0
    def remove(self, item):
        """Precondition: item is in self.
        Raises: KeyError if item is not in self.
        postcondition: item is removed from self."""
        if not item in self:
            raise KeyError("Item not in tree.""")

        # Helper function to adjust placement of an item
        def liftMaxInLeftSubtreeToTop(top):
            # Replace top's datum with the maximum datum in the left subtree
            # Pre:  top has a left child
            # Post: the maximum node in top's left subtree
            #       has been removed
            # Post: top.data = maximum value in top's left subtree
            parent = top
            currentNode = top.left
            while not currentNode.right == None:
                parent = currentNode
                currentNode = currentNode.right
            top.data = currentNode.data
            if parent == top:
                top.left = currentNode.left
            else:
                parent.right = currentNode.left

        # Begin main part of the method
        if self.isEmpty(): return None
        
        # Attempt to locate the node containing the item
        itemRemoved = None
        preRoot = BSTNode(None)
        preRoot.left = self._root
        parent = preRoot
        direction = 'L'
        currentNode = self._root
        while not currentNode == None:
            if currentNode.data == item:
                itemRemoved = currentNode.data
                break
            parent = currentNode
            if currentNode.data > item:
                direction = 'L'
                currentNode = currentNode.left
            else:
                direction = 'R'
                currentNode = currentNode.right
                
        # Return None if the item is absent
        if itemRemoved == None: return None
        
        # The item is present, so remove its node

        # Case 1: The node has a left and a right child
        #         Replace the node's value with the maximum value in the
        #         left subtree
        #         Delete the maximium node in the left subtree
        if not currentNode.left == None \
           and not currentNode.right == None:
            liftMaxInLeftSubtreeToTop(currentNode)
        else:
            
        # Case 2: The node has no left child
            if currentNode.left == None:
                newChild = currentNode.right
                
        # Case 3: The node has no right child
            else:
                newChild = currentNode.left
                
        # Case 2 & 3: Tie the parent to the new child
            if direction == 'L':
                parent.left = newChild
            else:
                parent.right = newChild
            
        # All cases: Reset the root (if it hasn't changed no harm done)
        #            Decrement the collection's size counter
        #            Return the item
        self._size -= 1
        if self.isEmpty():
            self._root = None
        else:
            self._root = preRoot.left
        return itemRemoved