Queries to calculate sum of the path from root to a given node in given Binary Tree | C ++ program for the above approach ; Function to find the sum of the path from root to the current node ; Sum of nodes in the path ; Iterate until root is reached ; Update the node value ; Print the resultant sum ; Function to print the path sum for each query ; Traverse the queries ; Driver Code ; arraylist to store integers
#include <iostream> NEW_LINE #include <vector> NEW_LINE 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 ; }