January 07, 2025 |4.4K Views

    Sum of k smallest elements in BST

      Share   Like
    Description
    Discussion

    The idea is to traverse BST in inorder traversal. Note that Inorder traversal of BST accesses elements in sorted (or increasing) order. While traversing, we keep track of count of visited Nodes and keep adding Nodes until the count becomes k. 
    Input :  K = 3


                 8
               /   \
              7     10
            /      /   \
           2      9     13


    Output : 17


    Explanation : Kth smallest element is 8 so sum of all
                 element smaller than or equal to 8 are
                 2 + 7 + 8

    Sum of k smallest elements in BST : https://www.geeksforgeeks.org/sum-k-smallest-elements-bst/