how to search binary sort tree in python

 How to search binary sort tree in python

To search a binary search tree in Python, you can use a recursive function that traverses the tree and compares the value being searched for with the value of each node. If the value being searched for is less than the value of the current node, the function searches the left subtree. If the value being searched for is greater than the value of the current node, the function searches the right subtree. If the value being searched for is equal to the value of the current node, the function returns the node.

Here is an example of how you might implement a search function for a binary search tree in Python:

class Node:
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def search(self, data):
        def search_node(node, data):
            if node is None:
                return None
            if data == node.data:
                return node
            if data < node.data:
                return search_node(node.left, data)
            if data > node.data:
                return search_node(node.right, data)

        return search_node(self.root, data)

bst = BinarySearchTree()
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
bst.root = node2
node2.left = node1
node2.right = node3
result = bst.search(1)
print(result.data) # Outputs 1

In this example, the search method takes a data value as input and returns the node with that data value, if it exists in the binary search tree. It does this by calling a helper function `search_node` recursively, passing it the root node of the tree and the data value being searched for. The `search_node` function compares the data value being searched for with the value of the current node, and then either returns the node, searches the left subtree, or searches the right subtree accordingly. If the data value is not found in the tree, the function returns `None`.


Post a Comment

0 Comments