Queries to calculate sum of the path from root to a given node in given Binary Tree
Last Updated :
29 Oct, 2023
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;
int findPathSum( int n) {
int sum = 0;
while (n != 1) {
sum += n;
n /= 2;
}
sum += 1;
return sum;
}
vector< int > findPathSums(vector< int >& arr) {
vector< int > pathSums;
for ( int n : arr) {
int pathSum = findPathSum(n);
pathSums.push_back(pathSum);
}
return pathSums;
}
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 {
static int findPathSum( int n) {
int sum = 0 ;
while (n != 1 ) {
sum += n;
n /= 2 ;
}
sum += 1 ;
return sum;
}
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;
}
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
def find_path_sum(n):
sum = 0
while n ! = 1 :
sum + = n
n / / = 2
sum + = 1
return sum
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
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 {
static int findPathSum( int n)
{
int sum = 0;
while (n != 1) {
sum += n;
n /= 2;
}
sum += 1;
return sum;
}
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;
}
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 findPathSum(n) {
let sum = 0;
while (n !== 1) {
sum += n;
n = Math.floor(n / 2);
}
sum += 1;
return sum;
}
function findPathSums(arr) {
const pathSums = [];
for (const n of arr) {
const pathSum = findPathSum(n);
pathSums.push(pathSum);
}
return pathSums;
}
const arr = [1, 4, 20];
const pathSums = findPathSums(arr);
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++
#include <iostream>
#include <vector>
using namespace std;
void sumOfNodeInAPath( int node_value)
{
int sum_of_node = 0;
while (node_value) {
sum_of_node += node_value;
node_value /= 2;
}
cout << sum_of_node;
return ;
}
void findSum(vector< int > Q)
{
for ( int i = 0; i < Q.size(); i++) {
int node_value = Q[i];
sumOfNodeInAPath(node_value);
cout << " " ;
}
}
int main()
{
vector< int > arr = { 1, 5, 20, 100 };
findSum(arr);
return 0;
}
|
Java
import java.io.*;
import java.util.ArrayList;
class GFG {
public static void sumOfNodeInAPath( int node_value)
{
int sum_of_node = 0 ;
while (node_value > 0 ) {
sum_of_node += node_value;
node_value /= 2 ;
}
System.out.print(sum_of_node);
}
public static void findSum(ArrayList<Integer> Q)
{
for ( int i = 0 ; i < Q.size(); i++) {
int node_value = Q.get(i);
sumOfNodeInAPath(node_value);
System.out.print( " " );
}
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<>();
arr.add( 1 );
arr.add( 5 );
arr.add( 20 );
arr.add( 100 );
findSum(arr);
}
}
|
Python3
def sumOfNodeInAPath(node_value):
sum_of_node = 0
while (node_value):
sum_of_node + = node_value
node_value / / = 2
print (sum_of_node, end = " " )
def findSum(Q):
for i in range ( len (Q)):
node_value = Q[i]
sumOfNodeInAPath(node_value)
print (end = "")
arr = [ 1 , 5 , 20 , 100 ]
findSum(arr)
|
C#
using System;
using System.Collections.Generic;
class GFG{
public static void sumOfNodeInAPath( int node_value)
{
int sum_of_node = 0;
while (node_value > 0) {
sum_of_node += node_value;
node_value /= 2;
}
Console.Write(sum_of_node);
}
public static void findSum(List< int > Q)
{
for ( int i = 0; i < Q.Count ; i++) {
int node_value = Q[i];
sumOfNodeInAPath(node_value);
Console.Write( " " );
}
}
static public void Main()
{
List< int > arr = new List< int >();
arr.Add(1);
arr.Add(5);
arr.Add(20);
arr.Add(100);
findSum(arr);
}
}
|
Javascript
<script>
function sumOfNodeInAPath(node_value)
{
let sum_of_node = 0;
while (node_value) {
sum_of_node += node_value;
node_value = Math.floor(node_value / 2 );
}
document.write(sum_of_node);
return ;
}
function findSum( Q)
{
for (let i = 0; i < Q.length; i++) {
let node_value = Q[i];
sumOfNodeInAPath(node_value);
document.write( " " );
}
}
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
Find the path from root to the given nodes of a tree for multiple queries
Given a tree with N vertices numbered from 0 to N - 1 (0th node is the root node). Also, given q queries containing nodes in the tree. The task is to find the path from the root node to the given node for multiple queries. Examples: Input: N = 6, q[] = {2, 4} Tree: 0 / \ 1 2 | 3 / \ 4 5 Output: 0 2
10 min read
Print path from a node to root of given Complete Binary Tree
Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form: The Binary Tree is a Complete Binary Tree up to the level of the Nth node.The nodes are numbered 1 to N, starting from the root as 1.The structure of the Tree is as follows: 1 / \ 2
4 min read
Path from the root node to a given node in an N-ary Tree
Given an integer N and an N-ary Tree of the following form: Every node is numbered sequentially, starting from 1, till the last level, which contains the node N.The nodes at every odd level contains 2 children and nodes at every even level contains 4 children. The task is to print the path from the
10 min read
Sum of nodes in the path from root to N-th node in given Tree
Given an integer n which needs to be present as a value in a node in the last level of a Binary Tree rooted at 1 having nodes numbered from root to the last level by increments of 1. The nodes at every odd level contain 2 children and nodes at every even level contain 4 children. The task is to find
11 min read
Maximize sum of path from the Root to a Leaf node in N-ary Tree
Given a generic tree consisting of n nodes, the task is to find the maximum sum of the path from the root to the leaf node. Examples: Input: Output: 12Explanation: The path sum to every leaf from the root are:For node 4: 1 -> 2 -> 4 = 7For node 5: 1 -> 2 -> 5 = 8For node 6: 1 -> 3 -
5 min read
Count nodes having smallest value in the path from root to itself in a Binary Tree
Given a Binary Tree, the task is to count the number of nodes in the given Binary Tree such that the path from the root to that node contains node with value greater than or equal to that node. Examples: Input: 6 / \ 7 4 / \ / \ 3 7 1 2 Output: 5 Explanation: Root node 6 is considered as its the onl
8 min read
Count the number of paths from root to leaf of a Binary tree with given XOR value
Given a value K and a binary tree, we have to find out the total number of paths from the root to leaf nodes having XOR of all its nodes along the path equal to K.Examples: Input: K = 6 2 / \ 1 4 / \ 10 5 Output: 2 Explanation: Subtree 1: 2 \ 4 This particular path has 2 nodes, 2 and 4 and (2 xor 4)
8 min read
Find sum of all nodes of the given perfect binary tree
Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a progr
11 min read
Print path from root to all nodes in a Complete Binary Tree
Given a number N which is the total number of nodes in a complete binary tree where nodes are number from 1 to N sequentially level-wise. The task is to write a program to print paths from root to all of the nodes in the Complete Binary Tree.For N = 3, the tree will be: 1 / \ 2 3 For N = 7, the tree
9 min read
Count of root to leaf paths in a Binary Tree that form an AP
Given a Binary Tree, the task is to count all paths from root to leaf which forms an Arithmetic Progression. Examples: Input: Output: 2 Explanation: The paths that form an AP in the given tree from root to leaf are: 1->3->5 (A.P. with common difference 2)1->6->11 (A.P. with common differ
7 min read