Queries to calculate sum of the path from root to a given node in given Binary Tree
Last Updated :
23 Jul, 2025
Given an infinite complete binary tree rooted at node 1, where every ith node has two children, with values 2 * i and 2 * (i + 1). Given another array arr[] consisting of N positive integers, the task for each array element arr[i] is to find the sum of the node values that occur in a path from the root node to the node arr[i].
Examples:
Input: arr[] = {3, 10}
Output: 4 18
Explanation:
Node 3: The path is 3 -> 1. Therefore, the sum of the path is 4.
Node 10: The path is 10 -> 5 -> 2 -> 1. Therefore, the sum of node is 18.
Input: arr[] = {1, 4, 20}
Output: 1 7 38
Explanation:
Node 1: The path is 1. Therefore, the sum of the path is 1.
Node 4: The path is 4 -> 2 -> 1. Therefore, the sum of node is 7.
Node 20: The path is 20 -> 10 -> 5 -> 2 -> 1. Therefore, the sum of node is 38.
Naive Approach: The simplest approach is to perform DFS Traversal for each array element arr[i] to find its path from the current node to the root and print the sum of the node values in that path.
Time Complexity: O(N * H), where H is the maximum height of the tree.
Auxiliary Space: O(H)
Optimized Approach: In this approach we will be creating a function to find the sum of node values along the path for each element in the given array arr[] and a function to find the sum of node values along the path from the root node to a given node.
Step by step algorithm:
- Initialize sum to 0.
- Traverse the binary tree from the given node to the root node.
- At each node, add the node value to the sum.
- Update the current node to its parent node.
- Repeat steps 3-4 until the current node is the root node.
- Add the root node value to the sum.
- Return the sum.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the sum of node values along the path
// from the root node to a given node
int findPathSum(int n) {
int sum = 0;
while (n != 1) {
sum += n;
n /= 2;
}
sum += 1; // Add the root node value
return sum;
}
// Function to find the sum of node values along the path
// for each element in the given array arr[]
vector<int> findPathSums(vector<int>& arr) {
vector<int> pathSums;
for (int n : arr) {
int pathSum = findPathSum(n);
pathSums.push_back(pathSum);
}
return pathSums;
}
// Driver code
int main() {
vector<int> arr = {1, 4, 20};
vector<int> pathSums = findPathSums(arr);
for (int sum : pathSums) {
cout << sum << " ";
}
cout << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Function to find the sum of node values along the path
// from the root node to a given node
static int findPathSum(int n) {
int sum = 0;
while (n != 1) {
sum += n;
n /= 2;
}
sum += 1; // Add the root node value
return sum;
}
// Function to find the sum of node values along the path
// for each element in the given array arr[]
static List<Integer> findPathSums(List<Integer> arr) {
List<Integer> pathSums = new ArrayList<>();
for (int n : arr) {
int pathSum = findPathSum(n);
pathSums.add(pathSum);
}
return pathSums;
}
// Driver code
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(1, 4, 20);
List<Integer> pathSums = findPathSums(arr);
for (int sum : pathSums) {
System.out.print(sum + " ");
}
System.out.println();
}
}
Python3
# Function to find the sum of node values along the path
# from the root node to a given node
def find_path_sum(n):
sum = 0
while n != 1:
sum += n
n //= 2
sum += 1 # Add the root node value
return sum
# Function to find the sum of node values along the path
# for each element in the given array arr[]
def find_path_sums(arr):
path_sums = []
for n in arr:
path_sum = find_path_sum(n)
path_sums.append(path_sum)
return path_sums
# Driver code
if __name__ == "__main__":
arr = [1, 4, 20]
path_sums = find_path_sums(arr)
for sum in path_sums:
print(sum, end=" ")
print()
C#
using System;
using System.Collections.Generic;
class GFG {
// Function to find the sum of node values along the
// path from the root node to a given node
static int findPathSum(int n)
{
int sum = 0;
while (n != 1) {
sum += n;
n /= 2;
}
sum += 1; // Add the root node value
return sum;
}
// Function to find the sum of node values along the
// path for each element in the given array arr[]
static List<int> findPathSums(List<int> arr)
{
List<int> pathSums = new List<int>();
foreach(int n in arr)
{
int pathSum = findPathSum(n);
pathSums.Add(pathSum);
}
return pathSums;
}
// Driver code
public static void Main(string[] args)
{
List<int> arr = new List<int>{ 1, 4, 20 };
List<int> pathSums = findPathSums(arr);
foreach(int sum in pathSums)
{
Console.Write(sum + " ");
}
Console.WriteLine();
}
}
JavaScript
// Function to find the sum of node values along the path
// from the root node to a given node
function findPathSum(n) {
let sum = 0;
while (n !== 1) {
sum += n;
n = Math.floor(n / 2);
}
sum += 1; // Add the root node value
return sum;
}
// Function to find the sum of node values along the path
// for each element in the given array arr[]
function findPathSums(arr) {
const pathSums = [];
for (const n of arr) {
const pathSum = findPathSum(n);
pathSums.push(pathSum);
}
return pathSums;
}
// Driver code
const arr = [1, 4, 20];
const pathSums = findPathSums(arr);
// Print the path sums on the same line
console.log(pathSums.join(" "));
Time complexity: O(NlogN), where N is the number of elements in the given array arr.
Auxiliary Space: O(N), where N is the number of elements in the given array arr.
Efficient Approach: The above approach can also be optimized based on the observation that the parent of the node with value N contains the value N/2. Follow the steps below to solve the problem:
- Initialize a variable, say sumOfNode, to store the sum of nodes in a path.
- Traverse the array arr[i] and perform the following steps:
- For each element arr[i], update the value of sumOfNode as sumOfNode + X and update arr[i] as arr[i] / 2.
- Repeat the above steps while arr[i] is greater than 0.
- Print the value of sumOfNode as the result for each array element arr[i].
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <iostream>
#include <vector>
using namespace std;
// Function to find the sum of the
// path from root to the current node
void sumOfNodeInAPath(int node_value)
{
// Sum of nodes in the path
int sum_of_node = 0;
// Iterate until root is reached
while (node_value) {
sum_of_node += node_value;
// Update the node value
node_value /= 2;
}
// Print the resultant sum
cout << sum_of_node;
return;
}
// Function to print the path
// sum for each query
void findSum(vector<int> Q)
{
// Traverse the queries
for (int i = 0; i < Q.size(); i++) {
int node_value = Q[i];
sumOfNodeInAPath(node_value);
cout << " ";
}
}
// Driver Code
int main()
{
vector<int> arr = { 1, 5, 20, 100 };
findSum(arr);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.ArrayList;
class GFG {
// Function to find the sum of the
// path from root to the current node
public static void sumOfNodeInAPath(int node_value)
{
// Sum of nodes in the path
int sum_of_node = 0;
// Iterate until root is reached
while (node_value > 0) {
sum_of_node += node_value;
// Update the node value
node_value /= 2;
}
// Print the resultant sum
System.out.print(sum_of_node);
}
// Function to print the path
// sum for each query
public static void findSum(ArrayList<Integer> Q)
{
// Traverse the queries
for (int i = 0; i < Q.size(); i++) {
int node_value = Q.get(i);
sumOfNodeInAPath(node_value);
System.out.print(" ");
}
}
// Driver Code
public static void main(String[] args)
{
// arraylist to store integers
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(5);
arr.add(20);
arr.add(100);
findSum(arr);
}
}
// This code is contributed by aditya7409.
Python3
# Python program for the above approach
# Function to find the sum of the
# path from root to the current node
def sumOfNodeInAPath(node_value):
# Sum of nodes in the path
sum_of_node = 0
# Iterate until root is reached
while (node_value):
sum_of_node += node_value
# Update the node value
node_value //= 2
# Print the resultant sum
print(sum_of_node, end = " ")
# Function to print the path
# sum for each query
def findSum(Q):
# Traverse the queries
for i in range(len(Q)):
node_value = Q[i]
sumOfNodeInAPath(node_value)
print(end = "")
# Driver Code
arr = [1, 5, 20, 100]
findSum(arr)
# This code is contributed by shubhamsingh10
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the sum of the
// path from root to the current node
public static void sumOfNodeInAPath(int node_value)
{
// Sum of nodes in the path
int sum_of_node = 0;
// Iterate until root is reached
while (node_value > 0) {
sum_of_node += node_value;
// Update the node value
node_value /= 2;
}
// Print the resultant sum
Console.Write(sum_of_node);
}
// Function to print the path
// sum for each query
public static void findSum(List<int> Q)
{
// Traverse the queries
for (int i = 0; i < Q.Count ; i++) {
int node_value = Q[i];
sumOfNodeInAPath(node_value);
Console.Write(" ");
}
}
// Driver Code
static public void Main()
{
// arraylist to store integers
List<int> arr = new List<int>();
arr.Add(1);
arr.Add(5);
arr.Add(20);
arr.Add(100);
findSum(arr);
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// JavaScript program to count frequencies of array items
// Function to find the sum of the
// path from root to the current node
function sumOfNodeInAPath(node_value)
{
// Sum of nodes in the path
let sum_of_node = 0;
// Iterate until root is reached
while (node_value) {
sum_of_node += node_value;
// Update the node value
node_value = Math.floor(node_value / 2 );
}
// Print the resultant sum
document.write(sum_of_node);
return;
}
// Function to print the path
// sum for each query
function findSum( Q)
{
// Traverse the queries
for (let i = 0; i < Q.length; i++) {
let node_value = Q[i];
sumOfNodeInAPath(node_value);
document.write(" ");
}
}
// Driver Code
let arr = [ 1, 5, 20, 100 ];
findSum(arr);
</script>
Time Complexity: O(N*log X), where X is the maximum element of the array.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem