Python Program to Find the Kth Smallest Element in a BST

This program defines a Binary Search Tree (BST) and a method to find the kth smallest element within it using an in-order traversal. The BST nodes are defined with the class TreeNode, each having a value and pointers to left and right child nodes.


class TreeNode:
    """Node of a Binary Search Tree."""
    def __init__(self, x):
        """
        Initialize the tree node.
        
        :param x: int, the integer value of the node
        """
        self.val = x
        self.left = None
        self.right = None

class Solution:
    """Solution class to handle tree operations."""
    def kthSmallest(self, root, k):
        """
        Find the kth smallest element in a BST.
        
        :param root: TreeNode, the root node of the BST
        :param k: int, the 'kth' position to find the smallest element
        :return: int, the kth smallest element in the BST
        """
        # Array to store the in-order traversal
        elements = []
        
        # Helper function to perform in-order traversal
        def in_order_traverse(node):
            """Recursive in-order traversal to access BST in sorted order."""
            if not node:
                return
            in_order_traverse(node.left)
            elements.append(node.val)
            in_order_traverse(node.right)
        
        # Perform the in-order traversal of the tree
        in_order_traverse(root)
        
        # Return the kth smallest element
        return elements[k-1] if k <= len(elements) else None

# Example Usage
if __name__ == "__main__":
    # Create a BST
    root = TreeNode(5)
    root.left = TreeNode(3)
    root.right = TreeNode(6)
    root.left.left = TreeNode(2)
    root.left.right = TreeNode(4)
    root.left.left.left = TreeNode(1)
    
    # Instance of Solution
    sol = Solution()
    
    # Find 3rd smallest element
    kth_smallest = sol.kthSmallest(root, 3)
    print(f"The 3rd smallest element in the BST is: {kth_smallest}")

The above program initializes a basic BST and finds the kth smallest element. The Solution class contains the method kthSmallest, which performs an in-order traversal of the BST, collecting elements in a list in their inherent sorted order. The kth smallest element is then accessed directly from the list.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)