Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of specially balanced nodes from a given Binary Tree
Next article icon

Sum of nodes in a Binary Search Tree with values from a given range

Last Updated : 21 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree consisting of n nodes and two positive integers l and r, the task is to find the sum of values of all the nodes that lie in the range [l, r].

Examples:

Input:

sum-of-nodes-in-a-binary-search-tree-with-values-from-a-given-range-1

Output: 32
Explanation: The nodes in the given Tree that lies in the range [7, 15] are {7, 10, 15}. Therefore, the sum of nodes is 7 + 10 + 15 = 32.

Input:

sum-of-nodes-in-a-binary-search-tree-with-values-from-a-given-range-2

Output: 11
Explanation: The nodes in the given Tree that lies in the range [11, 15] is {11}. Therefore, the sum of node is 11.

Approach:

The idea to traverse the tree recursively. For each node, if it lies within the range, then return the sum of left subtree, right subtree and current node. If its value is less than range, then return the value of right subtree. Otherwise return the value of left subtree.

Below is the implementation of the above approach:

C++
// C++ program to calculate sum of  // nodes in a Binary Search Tree  // with values from a given range #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node *left, *right;     Node (int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // function to find sum of nodes that lie  // within a given range int nodeSum(Node *root, int low, int high) {          if (root == nullptr) return 0;          // If root value is less than range.     if (root->data < low) {         return nodeSum(root->right, low, high);     }          // If root value is greater than range.     else if (root->data > high) {         return nodeSum(root->left, low, high);     }          // If root value lies in the range.     int left = nodeSum(root->left, low, high);     int right = nodeSum(root->right, low, high);          return low + high + root->data; }  int main() {          // BST     //       22     //      /  \     //    12    30     //   /  \     //  8    20     Node* root = new Node(22);     root->left = new Node(12);     root->right = new Node(30);     root->left->left = new Node(8);     root->left->right = new Node(20);     int l = 10, h = 22;          cout << nodeSum(root, l, h) << endl;          return 0; } 
Java
// Java program to calculate sum of  // nodes in a Binary Search Tree  // with values from a given range  import java.util.ArrayList;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // function to find sum of nodes that lie      // within a given range     static int nodeSum(Node root, int low, int high) {         if (root == null) return 0;          // If root value is less than range.         if (root.data < low) {             return nodeSum(root.right, low, high);         }          // If root value is greater than range.         else if (root.data > high) {             return nodeSum(root.left, low, high);         }          // If root value lies in the range.         int left = nodeSum(root.left, low, high);         int right = nodeSum(root.right, low, high);          return left + right + root.data;     }      public static void main(String[] args) {          // BST         //       22         //      /  \         //    12    30         //   /  \         //  8    20         Node root = new Node(22);         root.left = new Node(12);         root.right = new Node(30);         root.left.left = new Node(8);         root.left.right = new Node(20);         int l = 10, h = 22;          System.out.println(nodeSum(root, l, h));     } } 
Python
# Python program to calculate sum of  # nodes in a Binary Search Tree  # with values from a given range  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # function to find sum of nodes that lie  # within a given range def nodeSum(root, low, high):     if root is None:         return 0      # If root value is less than range.     if root.data < low:         return nodeSum(root.right, low, high)      # If root value is greater than range.     elif root.data > high:         return nodeSum(root.left, low, high)      # If root value lies in the range.     left = nodeSum(root.left, low, high)     right = nodeSum(root.right, low, high)      return left + right + root.data  if __name__ == "__main__":      # BST     #       22     #      /  \     #    12    30     #   /  \     #  8    20     root = Node(22)     root.left = Node(12)     root.right = Node(30)     root.left.left = Node(8)     root.left.right = Node(20)     l = 10     h = 22      print(nodeSum(root, l, h)) 
C#
// C# program to calculate sum of  // nodes in a Binary Search Tree  // with values from a given range  using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // function to find sum of nodes that lie      // within a given range     static int nodeSum(Node root, int low, int high) {         if (root == null) return 0;          // If root value is less than range.         if (root.data < low) {             return nodeSum(root.right, low, high);         }          // If root value is greater than range.         else if (root.data > high) {             return nodeSum(root.left, low, high);         }          // If root value lies in the range.         int left = nodeSum(root.left, low, high);         int right = nodeSum(root.right, low, high);          return left + right + root.data;     }      static void Main(string[] args) {          // BST         //       22         //      /  \         //    12    30         //   /  \         //  8    20         Node root = new Node(22);         root.left = new Node(12);         root.right = new Node(30);         root.left.left = new Node(8);         root.left.right = new Node(20);         int l = 10, h = 22;          Console.WriteLine(nodeSum(root, l, h));     } } 
JavaScript
// JavaScript program to calculate sum of  // nodes in a Binary Search Tree  // with values from a given range  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // function to find sum of nodes that lie  // within a given range function nodeSum(root, low, high) {     if (root === null) return 0;      // If root value is less than range.     if (root.data < low) {         return nodeSum(root.right, low, high);     }      // If root value is greater than range.     else if (root.data > high) {         return nodeSum(root.left, low, high);     }      // If root value lies in the range.     let left = nodeSum(root.left, low, high);     let right = nodeSum(root.right, low, high);      return left + right + root.data; }  // BST //       22 //      /  \ //    12    30 //   /  \ //  8    20 let root = new Node(22); root.left = new Node(12); root.right = new Node(30); root.left.left = new Node(8); root.left.right = new Node(20); let l = 10, h = 22;  console.log(nodeSum(root, l, h)); 

Output
54 

Time Complexity: O(n), where n is the number of nodes in tree.
Auxiliary Space: O(h), where h is the height of tree.

Related articles:

  • Print BST keys in the given range
  • Remove BST keys outside the given range


Next Article
Sum of specially balanced nodes from a given Binary Tree

C

CoderSaty
Improve
Article Tags :
  • DSA
  • Queue
  • Searching
  • Tree
  • Binary Search Trees
  • BST
  • Tree Traversals
  • tree-level-order
Practice Tags :
  • Queue
  • Searching
  • Tree

Similar Reads

  • Number of pairs with a given sum in a Binary Search Tree
    Given a Binary Search Tree, and a number X. The task is to find the number of distinct pairs of distinct nodes in BST with a sum equal to X. No two nodes have the same values. Examples: Input : X = 5 5 / \ 3 7 / \ / \ 2 4 6 8 Output : 1 {2, 3} is the only possible pair. Thus, the answer is equal to
    9 min read
  • Median of all nodes from a given range in a Binary Search Tree ( BST )
    Given a Binary Search Tree (BST)consisting of N nodes and two nodes A and B, the task is to find the median of all the nodes in the given BST whose values lie over the range [A, B]. Examples: Input: A = 3, B = 11 Output: 6Explanation:The nodes that lie over the range [3, 11] are {3, 4, 6, 8, 11}. Th
    10 min read
  • Sum of all the child nodes with even parent values in a Binary Tree
    Given a binary tree, the task is to find the sum of all the nodes whose parent is even.Examples: Input: 1 / \ 3 8 / \ 5 6 / 1Output: 11The only even nodes are 8 and 6 and the sum of their children is 5 + 6 = 11.Input: 2 / \ 3 8 / / \ 2 5 6 / \ 1 3Output: 253 + 8 + 5 + 6 + 3 = 25Approach: Initialise
    14 min read
  • Queries to find the sum of weights of all nodes with vertical width from given range in a Binary Tree
    Given a Binary Tree consisting of N nodes having values in the range [0, N - 1] rooted as 0, an array wt[] of size N where wt[i] is the weight of the ith node and a 2D array Q[][] consisting of queries of the type {L, R}, the task for each query is to find the sum of weights of all nodes whose verti
    11 min read
  • Sum of specially balanced nodes from a given Binary Tree
    Given a Binary Tree, the task is to find the sum of all the specially balanced nodes in the given Binary Tree. A specially balanced node in a Binary Tree contains the sum of nodes of one subtree(either left or right) as even and the sum of the other subtree as odd.The nodes having only one child or
    13 min read
  • Sum of all nodes with smaller values at a distance K from a given node in a BST
    Given a Binary Search Tree, a target node in the BST, and an integer value K, the task is to find the sum of all nodes that are at a distance K from the target node whose value is less than the target node. Examples: Input: target = 7, K = 2 Output: 11Explanation:The nodes at a distance K(= 2) from
    15+ min read
  • Subtree with given sum in a Binary Tree
    You are given a binary tree and a given sum. The task is to check if there exists a subtree whose sum of all nodes is equal to the given sum. Examples: Input : key = 11 Output: TrueExplanation: sum of all nodes of subtree {2, 4, 5} = 11.Input : key = 6 Output: FalseExplanation: No subtree whose sum
    15 min read
  • Sum of cousins of a given node in a Binary Tree
    Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1. Note: It is given that all nodes have distinct values and the given node exists in the tree. Examples: Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 1
    11 min read
  • Find sum of all right leaves in a given Binary Tree
    Given a Binary Tree, the task is to find the sum of all right leaf nodes in it. Examples : Example1: Sum of all the right leaf nodes in the below tree is 2 + 5 + 7 = 15 Example2: Sum of all the right leaf nodes in the below tree is 5 + 8 = 13 Table of Content [Expected Approach - 1] Using Recursion
    14 min read
  • Sum of nodes in the right view of the given binary tree
    Given a binary tree, the task is to find the sum of the nodes which are visible in the right view. The right view of a binary tree is the set of nodes visible when the tree is viewed from the right.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6Output: 101 + 3 + 6 = 10Input: 1 / \ 2 3 \ 4 \ 5 \ 6Output: 19Ap
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences