Sum of all the numbers that are formed from root to leaf paths | C ++ program to find sum of all paths from root to leaves ; function to allocate new node with given data ; Returns sum of all root to leaf paths . The first parameter is root of current subtree , the second parameter is value of the number formed by nodes from root to this node ; Base case ; Update val ; if current node is leaf , return the current value of val ; recur sum of values for left and right subtree ; A wrapper function over treePathsSumUtil ( ) ; Pass the initial value as 0 as there is nothing above root ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; } ; node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = Node -> right = NULL ; return ( Node ) ; } int treePathsSumUtil ( node * root , int val ) { if ( root == NULL ) return 0 ; val = ( val * 10 + root -> data ) ; if ( root -> left == NULL && root -> right == NULL ) return val ; return treePathsSumUtil ( root -> left , val ) + treePathsSumUtil ( root -> right , val ) ; } int treePathsSum ( node * root ) { return treePathsSumUtil ( root , 0 ) ; } int main ( ) { node * root = newNode ( 6 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 2 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 7 ) ; root -> left -> right -> right = newNode ( 4 ) ; cout << " Sum ▁ of ▁ all ▁ paths ▁ is ▁ " << treePathsSum ( root ) ; return 0 ; }