BST
A binary search tree (BST) is a binary tree data structure in which each vertex has at most two children, referred to as the left and right child.
In a BST, the key values of vertices in the left subtree are less than the key value of the root, and the key values of nodes in the right subtree are greater than the key value of the root. This property allows for efficient search, insertion, and deletion operations, making BSTs useful for implementing algorithms such as binary search and various data structures like sets and maps.
BST implementation
python99123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566class TreeNode:def __init__(self, key):# Initialize a new TreeNode with a given key valueself.key = keyself.left = None # Initialize left child pointer to Noneself.right = None # Initialize right child pointer to Noneclass BST:def __init__(self):# Initialize an empty Binary Search Tree (BST) with no rootself.root = Nonedef insert(self, key):# Insert a new key into the BSTif self.root is None: # If the tree is empty, create a new root nodeself.root = TreeNode(key)else:self._insert_recursive(self.root, key) # Otherwise, call recursive insertiondef _insert_recursive(self, root, key):# Recursively insert the key into the appropriate position in the treeif key < root.key: # If the key is less than the current node's key, go leftif root.left is None: # If the left child is None, insert a new noderoot.left = TreeNode(key)else:self._insert_recursive(root.left, key) # Otherwise, continue recursion to the leftelif key > root.key: # If the key is greater than the current node's key, go rightif root.right is None: # If the right child is None, insert a new noderoot.right = TreeNode(key)else:self._insert_recursive(root.right, key) # Otherwise, continue recursion to the rightdef delete(self, key):# Delete a key from the BSTself.root = self._delete_recursive(self.root, key) # Call recursive deletiondef _delete_recursive(self, root, key):# Recursively delete the key from the treeif root is None: # If the tree is empty or key not found, return Nonereturn rootif key < root.key: # If the key is less than the current node's key, go leftroot.left = self._delete_recursive(root.left, key) # Recursively delete from the left subtreeelif key > root.key: # If the key is greater than the current node's key, go rightroot.right = self._delete_recursive(root.right, key) # Recursively delete from the right subtreeelse: # Key found, perform deletionif root.left is None: # If the left child is None, return the right childreturn root.rightelif root.right is None: # If the right child is None, return the left childreturn root.leftelse: # Node has both children, find successor and replace key with successorsuccessor = self._find_min(root.right)root.key = successor.keyroot.right = self._delete_recursive(root.right, successor.key)return rootdef search(self, key):# Search for a key in the BSTreturn self._search_recursive(self.root, key) # Call recursive searchdef _search_recursive(self, root, key):# Recursively search for the key in the treeif root is None or root.key == key: # If root is None or key found, return rootreturn rootif key < root.key: # If the key is less than the current node's key, search left subtreereturn self._search_recursive(root.left, key)return self._search_recursive(root.right, key) # Otherwise, search right subtree
Basic operations time complexity
Note
A balanced tree is a data structure in which the heights of the subtrees of any node differ by at most one. We will discuss it in more detail in the next sections.
Insertion:
Best and Average Case (O(log n)): In a balanced BST, insertion involves traversing down the tree from the root to find the appropriate position for the new node. At each level, the search space is divided in half, reducing the search time logarithmically with respect to the number of nodes;
Worst Case (O(n)): If the tree becomes unbalanced, such as when nodes are inserted in sorted order, the tree can degenerate into a linked list. In this case, the insertion operation becomes linear with respect to the number of nodes, as each new node is simply appended to the end of the list.
Deletion:
Best and Average Case (O(log n)): Similar to insertion, deletion in a balanced BST involves traversing down the tree to find the node to be deleted. The search space is divided in half at each level, resulting in a logarithmic time complexity;
Worst Case (O(n)): As with insertion, if the tree becomes unbalanced, deletion can degrade to O(n) time complexity. For example, deleting a node from a skewed tree may require traversing through most or all of the nodes.
Search:
Best and Average Case (O(log n)): The BST's structure allows for efficient search by recursively traversing down the tree from the root. The search space is halved at each level, leading to a logarithmic time complexity;
Worst Case (O(n)): In the worst case scenario, the tree is unbalanced, resulting in a linear search time. This occurs when the tree degenerates into a linked list, and the search traverses through most or all of the nodes.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme