Open In App

Sum of k smallest elements in BST

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given Binary Search Tree. The task is to find the sum of all elements smaller than and equal to kth smallest element.

Examples: 

Input:

Sum-of-k-smallest-elements-in-BST-1

Output: 17
Explanation: kth smallest element is 8 so sum of all element smaller than or equal to 8 are 2 + 7 + 8 = 17.

Input:

Sum-of-k-smallest-elements-in-BST-2

Output: 25
Explanation: kth smallest element is 8 so sum of all element smaller than or equal to 8 are 8 + 5 + 7 + 2 + 3 = 25.

[Naive Approach] Using Inorder Traversal – O(n) Time and O(n) Space

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

Below is the implementation of the above approach:

C++
// C++ program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Recursive function to calculate the sum of the 
// first k smallest elements
void calculateSum(Node* root, int& k, int& ans) {
    
    if (root->left != nullptr) {
        calculateSum(root->left, k, ans);
    }

    if (k > 0) {
        ans += root->data;
        k--;
    } 
    else {
        return;
    }

    if (root->right != nullptr) {
        calculateSum(root->right, k, ans);
    }
}

// Function to find the sum of the first 
// k smallest elements
int sum(Node* root, int k) {
    
    int ans = 0;
    calculateSum(root, k, ans);
    return ans;
}

int main() {

    // Input BST
    //         8
    //       /   \
    //      7     10
    //    /      /  \
    //   2      9    13
    Node* root = new Node(8);
    root->left = new Node(7);
    root->right = new Node(10);
    root->left->left = new Node(2);
    root->right->left = new Node(9);
    root->right->right = new Node(13);

    int k = 3;
    cout << sum(root, k) << "\n";

    return 0;
}
C
// C program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Recursive function to calculate the sum of
// the first k smallest elements
void calculateSum(struct Node* root, int* k, int* ans) {
    
    if (root->left != NULL) {
        calculateSum(root->left, k, ans);
    }

    if (*k > 0) {
        *ans += root->data;
        (*k)--;
    } 
    else {
        return;
    }

    if (root->right != NULL) {
        calculateSum(root->right, k, ans);
    }
}

// Function to find the sum of the first 
// k smallest elements
int sum(struct Node* root, int k) {
    int ans = 0;
    calculateSum(root, &k, &ans);
    return ans;
}

struct Node* newNode(int data) {
    struct Node* node 
      = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = node->right = NULL;
    return node;
}

int main() {

    // Input BST
    //         8
    //       /   \
    //      7     10
    //    /      /  \
    //   2      9    13
    struct Node* root = newNode(8);
    root->left = newNode(7);
    root->right = newNode(10);
    root->left->left = newNode(2);
    root->right->left = newNode(9);
    root->right->right = newNode(13);

    int k = 3;
    printf("%d\n", sum(root, k));  

    return 0;
}
Java
// Java program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // Recursive function to calculate the sum of the 
    // first k smallest elements
    static void calculateSum(Node root, int[] k, 
                                          int[] ans) {
        
        if (root.left != null) {
            calculateSum(root.left, k, ans);
        }

        if (k[0] > 0) {
            ans[0] += root.data;
            k[0]--;
        } 
        else {
            return;
        }

        if (root.right != null) {
            calculateSum(root.right, k, ans);
        }
    }

    // Function to find the sum of the first
    // k smallest elements
    static int sum(Node root, int k) {
        int[] ans = {0};
        int[] kArr = {k};
        calculateSum(root, kArr, ans);
        return ans[0];
    }

    public static void main(String[] args) {

        // Input BST
        //         8
        //       /   \
        //      7     10
        //    /      /  \
        //   2      9    13
        Node root = new Node(8);
        root.left = new Node(7);
        root.right = new Node(10);
        root.left.left = new Node(2);
        root.right.left = new Node(9);
        root.right.right = new Node(13);

        int k = 3;
        System.out.println(sum(root, k));  
    }
}
Python
# Python3 program to find Sum Of All 
# Elements smaller than or equal to 
# Kth Smallest Element In BST 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Recursive function to calculate the sum of 
# the first k smallest elements
def calculateSum(root, k, ans):
    if root.left is not None:
        calculateSum(root.left, k, ans)
    
    if k[0] > 0:
        ans[0] += root.data
        k[0] -= 1
    else:
        return

    if root.right is not None:
        calculateSum(root.right, k, ans)

# Function to find the sum of the first k 
# smallest elements
def sum_k_smallest(root, k):
    ans = [0]
    calculateSum(root, [k], ans)
    return ans[0]

if __name__ == "__main__":
  
    # Input BST
    #         8
    #       /   \
    #      7     10
    #    /      /  \
    #   2      9    13
    root = Node(8)
    root.left = Node(7)
    root.right = Node(10)
    root.left.left = Node(2)
    root.right.left = Node(9)
    root.right.right = Node(13)

    k = 3
    print(sum_k_smallest(root, k)) 
C#
// C# program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int data) {
        this.data = data;
        left = right = null;
    }
}

class GfG {

    // Recursive function to calculate the sum of 
    // the first k smallest elements
    static void CalculateSum(Node root, 
                                 ref int k, ref int ans) {
        
        if (root.left != null) {
            CalculateSum(root.left, ref k, ref ans);
        }

        if (k > 0) {
            ans += root.data;
            k--;
        } else {
            return;
        }

        if (root.right != null) {
            CalculateSum(root.right, ref k, ref ans);
        }
    }

    // Function to find the sum of the first k 
   // smallest elements
   	static int Sum(Node root, int k) {
        int ans = 0;
        CalculateSum(root, ref k, ref ans);
        return ans;
    }

    static void Main() {

        // Input BST
        //         8
        //       /   \
        //      7     10
        //    /      /  \
        //   2      9    13
        Node root = new Node(8);
        root.left = new Node(7);
        root.right = new Node(10);
        root.left.left = new Node(2);
        root.right.left = new Node(9);
        root.right.right = new Node(13);

        int k = 3;
        Console.WriteLine(Sum(root, k)); 
    }
}
JavaScript
// Javascript program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Recursive function to calculate the sum of the 
// first k smallest elements
function calculateSum(root, k, ans) {
    if (root.left !== null) {
        calculateSum(root.left, k, ans);
    }

    if (k.val > 0) {
        ans.val += root.data;
        k.val--;
    } 
    else {
        return;
    }

    if (root.right !== null) {
        calculateSum(root.right, k, ans);
    }
}

// Function to find the sum of the first k 
// smallest elements
function sumKSmallest(root, k) {
    let ans = { val: 0 };
    let kObj = { val: k };
    calculateSum(root, kObj, ans);
    return ans.val;
}

// Input BST
//         8
//       /   \
//      7     10
//    /      /  \
//   2      9    13
let root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);

let k = 3;
console.log(sumKSmallest(root, k));

Output
17

Time complexity: O(n), where n is the number of nodes in the Binary Search Tree, as the algorithm performs an inorder traversal visiting each node once.
Auxiliary Space: O(h), where h is the height of the tree, due to the recursive call stack. In the worst case (skewed tree), it can be O(n).

[Expected Approach] Using Morris Traversal – O(n) Time and O(1) Space

The idea is to use Morris Traversal , this method establishes temporary threads (links) to allow traversal and reverts these changes afterward to restore the original tree structure. By counting nodes during traversal, we can compute the cumulative sum of the k nodes visited.

Follow the steps below to solve the problem:

  • Initialize current as root, and counter, result to store the count and sum of elements found.
  • If current has no left child:
    • Increment counter and add current’s data to answer.
    • If counter == k, return answer.
    • Move to the right by updating current as current’right.
  • Otherwise:
    • Find the rightmost node in current’s left subtree (inorder predecessor) or a node whose right child is current.
  • If the right child of the found node is current, restore the original tree:
    • Set the right child of the node to NULL, increment counter, add current’s data to answer, and
    • if counter == k, return answer.
    • Move to the right by updating current as current’right.
  • Otherwise, set current as the right child of the rightmost node.

Below is implementation of above approach : 

C++
// C++ program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal 
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Function to find the sum of all elements 
// smaller than or equal to k-th smallest element
int sum(Node *root, int k) {
  
     Node* current = root;
    int count = 0, result = 0;

    while (current != nullptr) {
        if (current->left == nullptr) {
          
            // Visit this node
            count++;
            result += current->data;
            if (count == k) {
                return result;
            }
            // Move to the right subtree
            current = current->right;
        } 
       else {
          
            // Find the predecessor
            // (rightmost node in left subtree)
            Node* pre = current->left;
            while (pre->right != nullptr 
                         && pre->right != current) {
                pre = pre->right;
            }

            if (pre->right == nullptr) {
              
                // Establish thread/link from 
                // predecessor to current
                pre->right = current;
              
                // Move to the left subtree
                current = current->left;
            }
            else {
              
                // Revert the thread/link from
                // predecessor to current
                pre->right = nullptr;
              
                // Visit this node
                count++;
                result += current->data;
                if (count == k) {
                    return result;
                }
              
                // Move to the right subtree
                current = current->right;
            }
        }
    }
    return result; 
}

int main() {
  
    // Input BST
    //         8
    //       /   \
    //      7     10
    //    /      /  \
    //   2      9    13
    Node* root = new Node(8);
    root->left = new Node(7);
    root->right = new Node(10);
    root->left->left = new Node(2);
    root->right->left = new Node(9);
    root->right->right = new Node(13);

    int k = 3;
    cout << sum(root, k) << "\n"; 

    return 0;
}
C
// C program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

// Function to find the sum of all elements
// smaller than or equal to k-th smallest element
int sum(struct Node *root, int k) {
    struct Node *current = root;
    int count = 0, result = 0;

    while (current != NULL) {
        if (current->left == NULL) {
          
            // Visit this node
            count++;
            result += current->data;
            if (count == k) {
                return result;
            }
            // Move to the right subtree
            current = current->right;
        }
        else {
          
            // Find the predecessor 
            // (rightmost node in left subtree)
            struct Node *pre = current->left;
            while (pre->right != NULL 
                   && pre->right != current) {
                pre = pre->right;
            }

            if (pre->right == NULL) {
              
                // Establish thread/link from 
                // predecessor to current
                pre->right = current;
              
                // Move to the left subtree
                current = current->left;
            } 
            else {
             
                // Revert the thread/link from 
                // predecessor to current
                pre->right = NULL;
              
                // Visit this node
                count++;
                result += current->data;
                if (count == k) {
                    return result;
                }
              
                // Move to the right subtree
                current = current->right;
            }
        }
    }
    return result;
}

struct Node* createNode(int data) {
    struct Node* newNode 
      = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}

int main() {
  
    // Input BST
    //         8
    //       /   \
    //      7     10
    //    /      /  \
    //   2      9    13
    struct Node* root = createNode(8);
    root->left = createNode(7);
    root->right = createNode(10);
    root->left->left = createNode(2);
    root->right->left = createNode(9);
    root->right->right = createNode(13);

    int k = 3;
    printf("%d\n", sum(root, k));

    return 0;
}
Java
// Java program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Function to find the sum of all elements 
    // smaller than or equal to k-th smallest element
    static int sum(Node root, int k) {
        Node current = root;
        int count = 0, result = 0;

        while (current != null) {
            if (current.left == null) {
              
                // Visit this node
                count++;
                result += current.data;
                if (count == k) {
                    return result;
                }
                // Move to the right subtree
                current = current.right;
            } 
            else {
              
                // Find the predecessor 
                // (rightmost node in left subtree)
                Node pre = current.left;
                while (pre.right != null 
                       && pre.right != current) {
                    pre = pre.right;
                }

                if (pre.right == null) {
                  
                    // Establish thread/link from 
                    // predecessor to current
                    pre.right = current;
                  
                    // Move to the left subtree
                    current = current.left;
                } 
                else {
                  
                    // Revert the thread/link from
                    // predecessor to current
                    pre.right = null;
                  
                    // Visit this node
                    count++;
                    result += current.data;
                    if (count == k) {
                        return result;
                    }
                  
                    // Move to the right subtree
                    current = current.right;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
      
        // Input BST
        //         8
        //       /   \
        //      7     10
        //    /      /  \
        //   2      9    13
        Node root = new Node(8);
        root.left = new Node(7);
        root.right = new Node(10);
        root.left.left = new Node(2);
        root.right.left = new Node(9);
        root.right.right = new Node(13);

        int k = 3;
        System.out.println(sum(root, k));
    }
}
Python
# Python program to find Sum Of All Elements smaller
# than or equal to Kth Smallest Element In BST
# Using Morris Traversal
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Function to find the sum of all elements 
# smaller than or equal to k-th smallest element
def sum_kth_smallest(root, k):
    current = root
    count = 0
    result = 0

    while current:
        if current.left is None:
          
            # Visit this node
            count += 1
            result += current.data
            if count == k:
                return result
              
            # Move to the right subtree
            current = current.right
        else:
          
            # Find the predecessor 
            # (rightmost node in left subtree)
            pre = current.left
            while pre.right is not None and pre.right != current:
                pre = pre.right

            if pre.right is None:
              
                # Establish thread/link from 
                # predecessor to current
                pre.right = current
                
                # Move to the left subtree
                current = current.left
            else:
              
                # Revert the thread/link from 
                # predecessor to current
                pre.right = None
                
                # Visit this node
                count += 1
                result += current.data
                if count == k:
                    return result
                  
                # Move to the right subtree
                current = current.right
    
    return result

if __name__ == "__main__":
  
    # Input BST
    #         8
    #       /   \
    #      7     10
    #    /      /  \
    #   2      9    13
    root = Node(8)
    root.left = Node(7)
    root.right = Node(10)
    root.left.left = Node(2)
    root.right.left = Node(9)
    root.right.right = Node(13)

    k = 3
    print(sum_kth_smallest(root, k))
C#
// C# program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Function to find the sum of all elements 
    // smaller than or equal to k-th smallest element
    static int Sum(Node root, int k) {
        Node current = root;
        int count = 0, result = 0;

        while (current != null) {
            if (current.left == null) {
              
                // Visit this node
                count++;
                result += current.data;
                if (count == k) {
                    return result;
                }
              
                // Move to the right subtree
                current = current.right;
            } 
            else {
                // Find the predecessor 
                // (rightmost node in left subtree)
                Node pre = current.left;
                while (pre.right != null 
                        && pre.right != current) {
                    pre = pre.right;
                }

                if (pre.right == null) {
                  
                    // Establish thread/link from 
                    // predecessor to current
                    pre.right = current;
                  
                    // Move to the left subtree
                    current = current.left;
                } 
                else {
                  
                    // Revert the thread/link from 
                    // predecessor to current
                    pre.right = null;
                  
                    // Visit this node
                    count++;
                    result += current.data;
                    if (count == k) {
                        return result;
                    }
                  
                    // Move to the right subtree
                    current = current.right;
                }
            }
        }
        return result;
    }

    static void Main(string[] args) {
      
        // Input BST
        //         8
        //       /   \
        //      7     10
        //    /      /  \
        //   2      9    13
        Node root = new Node(8);
        root.left = new Node(7);
        root.right = new Node(10);
        root.left.left = new Node(2);
        root.right.left = new Node(9);
        root.right.right = new Node(13);

        int k = 3;
        Console.WriteLine(Sum(root, k));
    }
}
JavaScript
// JavaScript program to find Sum Of All Elements 
// smaller than or equal to Kth Smallest 
// Element In BST Using Morris Traversal
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

// Function to find the sum of all elements 
// smaller than or equal to k-th smallest element
function sum(root, k) {
  let current = root;
  let count = 0;
  let result = 0;

  while (current !== null) {
    if (current.left === null) {
    
      // Visit this node
      count++;
      result += current.data;
      if (count === k) {
        return result;
      }
      
      // Move to the right subtree
      current = current.right;
    } 
    else {
    
      // Find the predecessor (rightmost node in left subtree)
      let pre = current.left;
      while (pre.right !== null && pre.right !== current) {
        pre = pre.right;
      }

      if (pre.right === null) {
      
        // Establish thread/link from predecessor to current
        pre.right = current;
        
        // Move to the left subtree
        current = current.left;
      }
      else {
      
        // Revert the thread/link from predecessor to current
        pre.right = null;
        
        // Visit this node
        count++;
        result += current.data;
        if (count === k) {
          return result;
        }
        
        // Move to the right subtree
        current = current.right;
      }
    }
  }

  return result;
}

// Input BST
//         8
//       /   \
//      7     10
//    /      /  \
//   2      9    13
let root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);

let k = 3;
console.log(sum(root, k)); 

Output
17

Time Complexity: O(k), since we only traverse the tree until the k-th smallest element.
Auxiliary Space: O(1), for the iterative approach, as it uses a constant amount of space, with no additional data structures aside from a few variables.



Next Article

Similar Reads

  翻译: