Sum of nodes in the path from root to N-th node in given Tree
Last Updated :
03 Oct, 2024
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 the sum of node values in the path from the root to the node n.
Examples:
Input: n = 13

Output: 20
Explanation: The traversal from root 1 to node 13 is 1 -> 2 -> 4 -> 13. Therefore, sum of all nodes in the path = 1 + 2 + 4 + 13 = 20.
Input: n = 124
Output: 193
Explanation: The traversal from root 1 to node 124 is 1 -> 2 -> 6 -> 16 -> 44 -> 124. Therefore, sum of all nodes in the path = 1 + 2 + 6 + 16 + 44 + 124 = 193.
Approach:
The idea is to breaks down a binary-like tree into levels, calculates cumulative node counts (prefix sums), and uses binary search (lower_bound) to determine how far to traverse for node n. By adjusting the node position at each level, we can efficiently computes the final answer.
Follow the steps below to solve the problem:
- Initialize an array to store the number of nodes present in each level of the Tree, i.e. {1, 2, 8, 16, 64, 128 ....} and store it.
- Calculate prefix sum of the array i.e. {1 3 11 27 91 219 .......}
- Find the index ind in the prefix sum array which exceeds or is equal to n using lower_bound(). Therefore, ind indicates the number of levels that need to be traversed to reach node n.
- Initialize a variable curr = n and two variables finalAns = 0 and val.
- Decrement ind until it is less than or equal to 1 and keep updating val = temp - prefix[ind - 1].
- Update curr to prefix[ind - 2] + (val + 1) / 2 if ind is odd.
- Otherwise, update curr to prefix[ind - 2] + (val + 3) / 4 if ind is even.
- After completing the above steps, add n + 1 to finalAns and print it as the required answer.
Below is the implementation of the above approach:
C++
// C++ program to find sum of all nodes from root to n
#include <bits/stdc++.h>
using namespace std;
// Function to find sum of all nodes from root to n
int sumOfPathNodes(int n) {
// If n is equal to 1
if (n == 1) {
return 1;
}
// If n is equal to 2 or 3
else if (n == 2 || n == 3) {
return n + 1;
}
// Stores the number of nodes at (i + 1)-th level
vector<int> arr;
arr.push_back(1);
// Stores the number of nodes
int k = 1;
// Stores if the current level is even or odd
bool flag = true;
while (k < n) {
// If level is odd then nodes will
// be multiplied by two
if (flag == true) {
k *= 2;
flag = false;
} else {
// If level is even then nodes will
// be multiplied by four
k *= 4;
flag = true;
}
// If level with node n is reached
if (k > n) {
break;
}
// Push into vector
arr.push_back(k);
}
int len = arr.size();
vector<int> prefix(len);
prefix[0] = 1;
// Compute prefix sums of count of
// nodes in each level
for (int i = 1; i < len; ++i) {
prefix[i] = arr[i] + prefix[i - 1];
}
vector<int>::iterator it =
lower_bound(prefix.begin(), prefix.end(), n);
// Stores the level in which node n is present
int ind = it - prefix.begin();
// Stores the required sum
int finalAns = 0;
int curr = n;
while (ind > 1) {
int val = curr - prefix[ind - 1];
// If ind is odd
if (ind % 2 != 0) {
curr = prefix[ind - 2] + (val + 1) / 2;
} else {
// If ind is even
curr = prefix[ind - 2] + (val + 3) / 4;
}
--ind;
// Add temp to the sum
finalAns += curr;
}
// At end add n + 1 to final answer
finalAns += (n + 1);
return finalAns;
}
int main() {
int n = 13;
// Function call to calculate sum of nodes in
// the path from root to n-th node
cout << sumOfPathNodes(n) << endl;
return 0;
}
Java
// Java program to find sum of all nodes
// from root to n
import java.util.*;
class GfG {
// Function to find sum of all nodes from root to n
static int sumOfPathNodes(int n) {
// If n is equal to 1
if (n == 1) {
return 1;
}
// If n is equal to 2 or 3
else if (n == 2 || n == 3) {
return n + 1;
}
// Stores the number of nodes at (i + 1)-th level
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
// Stores the number of nodes
int k = 1;
// Stores if the current level is
// even or odd
boolean flag = true;
while (k < n) {
// If level is odd then nodes will
// be multiplied by two
if (flag) {
k *= 2;
flag = false;
}
// If level is even then nodes will
// be multiplied by four
else {
k *= 4;
flag = true;
}
// If level with node n is reached
if (k > n) {
break;
}
// Push into array
arr.add(k);
}
int len = arr.size();
int[] prefix = new int[len];
prefix[0] = 1;
// Compute prefix sums of count of
// nodes in each level
for (int i = 1; i < len; ++i) {
prefix[i] = arr.get(i) + prefix[i - 1];
}
int ind = Arrays.binarySearch(prefix, n);
if (ind < 0) {
ind = -ind - 1;
}
// Stores the required sum
int finalAns = 0;
int curr = n;
while (ind > 1) {
int val = curr - prefix[ind - 1];
// If ind is odd
if (ind % 2 != 0) {
curr = prefix[ind - 2] + (val + 1) / 2;
} else {
// If ind is even
curr = prefix[ind - 2] + (val + 3) / 4;
}
--ind;
// Add temp to the sum
finalAns += curr;
}
// At end add n + 1 to final answer
finalAns += (n + 1);
return finalAns;
}
public static void main(String[] args) {
int n = 13;
System.out.println(sumOfPathNodes(n));
}
}
Python
# Python program to find sum of all nodes from root to n
from bisect import bisect_left
# Function to find sum of all nodes from root to n
def sumOfPathNodes(n):
# If n is equal to 1
if n == 1:
return 1
# If n is equal to 2 or 3
elif n == 2 or n == 3:
return n + 1
# Stores the number of nodes at (i + 1)-th level
arr = [1]
# Stores the number of nodes
k = 1
# Stores if the current level is even or odd
flag = True
while k < n:
# If level is odd
if flag:
k *= 2
flag = False
# If level is even
else:
k *= 4
flag = True
# If level with node n is reached
if k > n:
break
# Push into the list
arr.append(k)
lenn = len(arr)
prefix = [0] * lenn
prefix[0] = 1
# Compute prefix sums of count of nodes in each level
for i in range(1, lenn):
prefix[i] = arr[i] + prefix[i - 1]
it = bisect_left(prefix, n)
# Stores the level in which node n is present
ind = it
# Stores the required sum
final_ans = 0
temp = n
while ind > 1:
val = temp - prefix[ind - 1]
if ind % 2 != 0:
temp = prefix[ind - 2] + (val + 1) // 2
else:
temp = prefix[ind - 2] + (val + 3) // 4
ind -= 1
# Add temp to the sum
final_ans += temp
final_ans += (n + 1)
return final_ans
n = 13
print(sumOfPathNodes(n))
C#
// C# program to find sum of all nodes
// from root to n
using System;
using System.Collections.Generic;
class GfG {
// Function to find sum of all nodes from root to n
static int sumOfPathNodes(int n) {
// If n is equal to 1
if (n == 1) {
return 1;
}
// If n is equal to 2 or 3
else if (n == 2 || n == 3) {
return n + 1;
}
// Stores the number of nodes at
// (i + 1)-th level
List<int> arr = new List<int>();
arr.Add(1);
// Stores the number of nodes
int k = 1;
// Stores if the current level is
// even or odd
bool flag = true;
while (k < n) {
// If level is odd then nodes will be
// multiplied by two
if (flag) {
k *= 2;
flag = false;
}
// If level is even then nodes will be
// multiplied by four
else {
k *= 4;
flag = true;
}
// If level with node n is reached
if (k > n) {
break;
}
// Push into the list
arr.Add(k);
}
int len = arr.Count;
int[] prefix = new int[len];
prefix[0] = 1;
// Compute prefix sums of count of
// nodes in each level
for (int i = 1; i < len; ++i) {
prefix[i] = arr[i] + prefix[i - 1];
}
int ind = Array.BinarySearch(prefix, n);
if (ind < 0)
ind = ~ind;
// Stores the required sum
int finalAns = 0;
int curr = n;
while (ind > 1) {
int val = curr - prefix[ind - 1];
// If ind is odd
if (ind % 2 != 0) {
curr = prefix[ind - 2] + (val + 1) / 2;
}
else {
// If ind is even
curr = prefix[ind - 2] + (val + 3) / 4;
}
--ind;
// Add temp to the sum
finalAns += curr;
}
// At end add n + 1 to final answer
finalAns += (n + 1);
return finalAns;
}
static void Main() {
int n = 13;
Console.WriteLine(sumOfPathNodes(n));
}
}
JavaScript
// JavaScript code to find sum of all nodes
// from root to n
// Function to find sum of all nodes from root to n
function sumOfPathNodes(n) {
// If n is equal to 1
if (n === 1) {
return 1;
}
// If n is equal to 2 or 3
else if (n === 2 || n === 3) {
return n + 1;
}
// Stores the number of nodes at (i + 1)-th level
let arr = [];
arr.push(1);
// Stores the number of nodes
let k = 1;
// Stores if the current level is even or odd
let flag = true;
while (k < n) {
// If level is odd
if (flag) {
k *= 2;
flag = false;
}
// If level is even
else {
k *= 4;
flag = true;
}
// If level with node n is reached
if (k > n) {
break;
}
// Push into array
arr.push(k);
}
let len = arr.length;
let prefix = new Array(len);
prefix[0] = 1;
// Compute prefix sums of count of nodes
// in each level
for (let i = 1; i < len; ++i) {
prefix[i] = arr[i] + prefix[i - 1];
}
let it = lowerBound(prefix, 0, len, n) + 1;
// Stores the level in which node n is present
let ind = it - prefix[0];
// Stores the required sum
let final_ans = 0;
let temp = n;
while (ind > 1) {
let val = temp - prefix[ind - 1];
if (ind % 2 !== 0) {
temp = prefix[ind - 2] + Math.floor((val + 1) / 2);
}
else {
temp = prefix[ind - 2] + Math.floor((val + 3) / 4);
}
--ind;
// Add temp to the sum
final_ans += temp;
}
final_ans += (n + 1);
return final_ans;
}
function lowerBound(a, low, high, element) {
while (low < high) {
let middle = low + Math.floor((high - low) / 2);
if (element > a[middle]) {
low = middle + 1;
} else {
high = middle;
}
}
return low;
}
let n = 13;
console.log(sumOfPathNodes(n));
Time Complexity: O(log n) , where n is give in input.
Auxiliary Space: O(log n)
Similar Reads
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 on the longest path from root to leaf node Given a binary tree containing n nodes. The task is to find the sum of all nodes on the longest path from root to leaf node. If two or more paths compete for the longest path, then the path having the maximum sum of nodes is considered.Examples:Â Input: root[] = [4, 2, 5, 1, 3]Output: 13Explanation:
15 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
Queries to calculate sum of the path from root to a given node in given Binary Tree 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 r
10 min read
Sum of nodes in the left 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 left view. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left.Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. The Left
13 min read