Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement a Binary Search Tree (BST) in Python?

I’m trying to implement a Binary Search Tree in Python. I understand the concept of BSTs, but I’m having trouble with the implementation.

Could someone provide a simple yet comprehensive example of a BST in Python? The BST should have methods for insertion, search, and in-order traversal.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Sure, here’s a simple implementation of a Binary Search Tree in Python:

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

def insert(root, key):
    if root is None:
        return Node(key)
    else:
        if root.val < key:
            root.right = insert(root.right, key)
        else:
            root.left = insert(root.left, key)
    return root

def inorder(root):
    if root:
        inorder(root.left)
        print(root.val),
        inorder(root.right)

def search(root, key):
    if root is None or root.val == key:
        return root
    if root.val < key:
        return search(root.right, key)
    return search(root.left, key)

# Driver code
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)

# Print in-order traversal of the BST
inorder(r)

This code first defines a Node class which will be used for individual nodes in the BST. The insert function is used to insert new nodes into the BST, the inorder function is used to print the BST in in-order traversal, and the search function is used to find a specific value in the BST.

Please note that this is a basic implementation and may need to be adjusted based on your specific use case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading