Open In App

Sum of nodes in the path from root to N-th node in given Tree

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

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));

Output
20

Time Complexity: O(log n) , where n is give in input.
Auxiliary Space: O(log n)


Next Article

Similar Reads