Sum of all the numbers that are formed from root to leaf paths
Last Updated :
21 Sep, 2023
Given a binary tree, where every node value is a Digit from 1-9. Find the sum of all the numbers which are formed from root to leaf paths.
For example, consider the following Binary Tree.
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
There are 4 leaves, hence 4 root to leaf paths:
Path Number
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Answer = 632 + 6357 + 6354 + 654 = 13997
The idea is to do a preorder traversal of the tree. In the preorder traversal, keep track of the value calculated till the current node, let this value be val. For every node, we update the val as val*10 plus the node’s data.
Implementation:
C++
#include <bits/stdc++.h>
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;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left, *right;
};
struct node* newNode( int data)
{
struct node* node = ( struct node*) malloc ( sizeof ( struct node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
int treePathsSumUtil( struct 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( struct node *root)
{
return treePathsSumUtil(root, 0);
}
int main()
{
struct 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);
printf ( "Sum of all paths is %d" , treePathsSum(root));
return 0;
}
|
Java
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree
{
Node root;
int treePathsSumUtil(Node node, int val)
{
if (node == null )
return 0 ;
val = (val * 10 + node.data);
if (node.left == null && node.right == null )
return val;
return treePathsSumUtil(node.left, val)
+ treePathsSumUtil(node.right, val);
}
int treePathsSum(Node node)
{
return treePathsSumUtil(node, 0 );
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 6 );
tree.root.left = new Node( 3 );
tree.root.right = new Node( 5 );
tree.root.right.right = new Node( 4 );
tree.root.left.left = new Node( 2 );
tree.root.left.right = new Node( 5 );
tree.root.left.right.right = new Node( 4 );
tree.root.left.right.left = new Node( 7 );
System.out.print( "Sum of all paths is " +
tree.treePathsSum(tree.root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def treePathsSumUtil(root, val):
if root is None :
return 0
val = (val * 10 + root.data)
if root.left is None and root.right is None :
return val
return (treePathsSumUtil(root.left, val) +
treePathsSumUtil(root.right, val))
def treePathsSum(root):
return treePathsSumUtil(root, 0 )
root = Node( 6 )
root.left = Node( 3 )
root.right = Node( 5 )
root.left.left = Node( 2 )
root.left.right = Node( 5 )
root.right.right = Node( 4 )
root.left.right.left = Node( 7 )
root.left.right.right = Node( 4 )
print ( "Sum of all paths is" , treePathsSum(root))
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class GFG
{
public Node root;
public virtual int treePathsSumUtil(Node node,
int val)
{
if (node == null )
{
return 0;
}
val = (val * 10 + node.data);
if (node.left == null && node.right == null )
{
return val;
}
return treePathsSumUtil(node.left, val) +
treePathsSumUtil(node.right, val);
}
public virtual int treePathsSum(Node node)
{
return treePathsSumUtil(node, 0);
}
public static void Main( string [] args)
{
GFG tree = new GFG();
tree.root = new Node(6);
tree.root.left = new Node(3);
tree.root.right = new Node(5);
tree.root.right.right = new Node(4);
tree.root.left.left = new Node(2);
tree.root.left.right = new Node(5);
tree.root.left.right.right = new Node(4);
tree.root.left.right.left = new Node(7);
Console.Write( "Sum of all paths is " +
tree.treePathsSum(tree.root));
}
}
|
Javascript
<script>
class node
{
constructor(data){
this .data = data;
this .left = this .right = null ;
}
}
function treePathsSumUtil(root,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);
}
function treePathsSum(root)
{
return treePathsSumUtil(root, 0);
}
let root = new node(6);
root.left = new node(3);
root.right = new node(5);
root.left.left = new node(2);
root.left.right = new node(5);
root.right.right = new node(4);
root.left.right.left = new node(7);
root.left.right.right = new node(4);
document.write( "Sum of all paths is " +treePathsSum(root));
</script>
|
Output
Sum of all paths is 13997
Time Complexity: The above code is a simple preorder traversal code that visits every node exactly once. Therefore, the time complexity is O(n) where n is the number of nodes in the given binary tree.
Auxiliary Space: O(n)
Another Approach: We can also solve this problem by first finding all the paths from the root to the leaf . Then we convert all paths into numbers. In the end, we will add those numbers.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node *left, *right;
Node( int val)
{
data = val;
left = right = NULL;
}
};
void treePathsSumUtil(Node* root, vector<string> currPath,
vector<vector<string>> &allPath)
{
if (root == NULL)
return ;
currPath.push_back((to_string)(root->data));
if (root->left == NULL && root->right == NULL)
allPath.push_back(currPath);
treePathsSumUtil(root->left, currPath, allPath);
treePathsSumUtil(root->right, currPath, allPath);
currPath.pop_back();
}
int treePathsSum(Node* root)
{
vector<vector<string>> allPath;
vector<string> v;
treePathsSumUtil(root, v, allPath);
int s = 0;
for ( auto pathNumber : allPath)
{
string k= "" ;
for ( auto x: pathNumber)
k = k+x;
s += stoi(k);
}
return s;
}
int main()
{
Node *root = new Node(6);
root->left = new Node(3);
root->right = new Node(5);
root->left->left = new Node(2);
root->left->right = new Node(5);
root->right->right = new Node(4);
root->left->right->left = new Node(7);
root->left->right->right = new Node(4);
cout<< "Sum of all paths is " <<treePathsSum(root);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static class Node {
int data;
Node left, right;
Node( int val)
{
data = val;
left = right = null ;
}
};
static void
treePathsSumUtil(Node root, ArrayList<String> currPath,
ArrayList<ArrayList<String> > allPath)
{
if (root == null )
return ;
currPath.add(( "" + root.data));
if (root.left == null && root.right == null )
allPath.add( new ArrayList<>(currPath));
treePathsSumUtil(root.left, currPath, allPath);
treePathsSumUtil(root.right, currPath, allPath);
currPath.remove(currPath.size() - 1 );
}
static int treePathsSum(Node root)
{
ArrayList<ArrayList<String> > allPath
= new ArrayList<>();
ArrayList<String> v = new ArrayList<>();
treePathsSumUtil(root, v, allPath);
int s = 0 ;
for (ArrayList<String> pathNumber : allPath) {
String k = "" ;
for (String x : pathNumber)
k += x;
s += Integer.parseInt(k);
}
return s;
}
public static void main(String[] args)
{
Node root = new Node( 6 );
root.left = new Node( 3 );
root.right = new Node( 5 );
root.left.left = new Node( 2 );
root.left.right = new Node( 5 );
root.right.right = new Node( 4 );
root.left.right.left = new Node( 7 );
root.left.right.right = new Node( 4 );
System.out.println( "Sum of all paths is "
+ treePathsSum(root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def treePathsSumUtil(root, currPath, allPath):
if root is None :
return
currPath.append( str (root.data))
if root.left is None and root.right is None :
allPath.append(currPath.copy())
treePathsSumUtil(root.left, currPath, allPath)
treePathsSumUtil(root.right, currPath, allPath)
del currPath[ - 1 ]
def treePathsSum(root):
allPath = []
treePathsSumUtil(root, [], allPath)
s = 0
for pathNumber in allPath:
k = "".join(pathNumber)
s + = int (k)
return s
root = Node( 6 )
root.left = Node( 3 )
root.right = Node( 5 )
root.left.left = Node( 2 )
root.left.right = Node( 5 )
root.right.right = Node( 4 )
root.left.right.left = Node( 7 )
root.left.right.right = Node( 4 )
print ( "Sum of all paths is" , treePathsSum(root))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int data;
public Node left, right;
public Node( int val)
{
data = val;
left = right = null ;
}
}
static void treePathsSumUtil(Node root, List< string > currPath, List<List< string >> allPath)
{
if (root == null )
return ;
currPath.Add(root.data.ToString());
if (root.left == null && root.right == null )
allPath.Add( new List< string >(currPath));
treePathsSumUtil(root.left, currPath, allPath);
treePathsSumUtil(root.right, currPath, allPath);
currPath.RemoveAt(currPath.Count - 1);
}
static int treePathsSum(Node root)
{
List<List< string >> allPath = new List<List< string >>();
List< string > v = new List< string >();
treePathsSumUtil(root, v, allPath);
int s = 0;
foreach (List< string > pathNumber in allPath)
{
string k = "" ;
foreach ( string x in pathNumber)
k += x;
s += int .Parse(k);
}
return s;
}
static void Main( string [] args)
{
Node root = new Node(6);
root.left = new Node(3);
root.right = new Node(5);
root.left.left = new Node(2);
root.left.right = new Node(5);
root.right.right = new Node(4);
root.left.right.left = new Node(7);
root.left.right.right = new Node(4);
Console.WriteLine( "Sum of all paths is " + treePathsSum(root));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function treePathsSumUtil(root, currPath, allPath) {
if (root === null ) {
return ;
}
currPath.push(String(root.data));
if (root.left === null && root.right === null ) {
allPath.push(currPath.slice());
}
treePathsSumUtil(root.left, currPath, allPath);
treePathsSumUtil(root.right, currPath, allPath);
currPath.pop();
}
function treePathsSum(root) {
let allPath = [];
treePathsSumUtil(root, [], allPath);
let s = 0;
for (const pathNumber of allPath) {
let k = pathNumber.join( "" );
s += Number(k);
}
return s;
}
let root = new Node(6);
root.left = new Node(3);
root.right = new Node(5);
root.left.left = new Node(2);
root.left.right = new Node(5);
root.right.right = new Node(4);
root.left.right.left = new Node(7);
root.left.right.right = new Node(4);
console.log( "Sum of all paths is" , treePathsSum(root));
|
Output
Sum of all paths is 13997
Time Complexity: Time Complexity of this approach will be O(n^2) because we are traversing the allPath and joining currPath to the allPath array .
Auxiliary Space: O(n)
Iterative Depth-First Search (DFS) using a Stack:
The basic idea behind the "Iterative Depth-First Search (DFS) using a Stack" approach is to traverse the binary tree iteratively in a depth-first manner while keeping track of the path sum from the root to the current node. We use a stack to store pairs of nodes and their corresponding path sums.
Follow the steps below to implement the above idea:
- Start with an initial sum value of 0 and create an empty stack.
- Push the root node onto the stack along with its value as the initial path sum.
- While the stack is not empty, do the following:
a. Pop a node and its corresponding path sum from the stack.
b. If the popped node is a leaf (i.e., it has no left and right children), add the path sum to the overall result.
c. If the popped node has a right child, push the right child onto the stack with the updated path sum. The updated path sum is obtained by multiplying the current path sum by 10 and adding the value of the right child.
d. If the popped node has a left child, push the left child onto the stack with the updated path sum. The updated path sum is obtained by multiplying the current path sum by 10 and adding the value of the left child.
- Once the stack is empty, return the overall result, which represents the sum of all the numbers formed from root to leaf paths.
Below is the implementation:
C++
#include <iostream>
#include <stack>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
long long treePathsSum(Node* root)
{
if (root == nullptr)
return 0;
long long sum = 0;
stack<pair<Node*, long long > > stk;
stk.push(
{ root,
root->data });
while (!stk.empty()) {
Node* currNode = stk.top().first;
long long currSum = stk.top().second;
stk.pop();
if (currNode->left == nullptr
&& currNode->right == nullptr) {
sum += currSum;
}
else {
if (currNode->right != nullptr) {
stk.push({ currNode->right,
(currSum * 10)
+ currNode->right->data });
}
if (currNode->left != nullptr) {
stk.push({ currNode->left,
(currSum * 10)
+ currNode->left->data });
}
}
}
return sum;
}
int main()
{
Node* root = new Node();
root->data = 6;
root->left = new Node();
root->left->data = 3;
root->left->left = new Node();
root->left->left->data = 2;
root->left->right = new Node();
root->left->right->data = 5;
root->left->right->left = new Node();
root->left->right->left->data = 7;
root->left->right->right = new Node();
root->left->right->right->data = 4;
root->right = new Node();
root->right->data = 5;
root->right->right = new Node();
root->right->right->data = 4;
long long result = treePathsSum(root);
cout
<< "Sum of numbers formed from root to leaf paths: "
<< result << endl;
return 0;
}
|
Java
import java.util.Stack;
import java.util.AbstractMap;
class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
public class TreePathSum {
static long treePathsSum(Node root) {
if (root == null )
return 0 ;
long sum = 0 ;
Stack<AbstractMap.SimpleEntry<Node, Long>> stk = new Stack<>();
stk.push( new AbstractMap.SimpleEntry<>(root, ( long ) root.data));
while (!stk.isEmpty()) {
Node currNode = stk.peek().getKey();
long currSum = stk.peek().getValue();
stk.pop();
if (currNode.left == null && currNode.right == null ) {
sum += currSum;
} else {
if (currNode.right != null ) {
stk.push( new AbstractMap.SimpleEntry<>(currNode.right, (currSum * 10 ) + currNode.right.data));
}
if (currNode.left != null ) {
stk.push( new AbstractMap.SimpleEntry<>(currNode.left, (currSum * 10 ) + currNode.left.data));
}
}
}
return sum;
}
public static void main(String[] args) {
Node root = new Node( 6 );
root.left = new Node( 3 );
root.left.left = new Node( 2 );
root.left.right = new Node( 5 );
root.left.right.left = new Node( 7 );
root.left.right.right = new Node( 4 );
root.right = new Node( 5 );
root.right.right = new Node( 4 );
long result = treePathsSum(root);
System.out.println( "Sum of numbers formed from root to leaf paths: " + result);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def treePathsSum(root):
if root is None :
return 0
sum = 0
stk = []
stk.append((root, root.data))
while stk:
currNode, currSum = stk.pop()
if currNode.left is None and currNode.right is None :
sum + = currSum
else :
if currNode.right:
stk.append((currNode.right, (currSum * 10 ) + currNode.right.data))
if currNode.left:
stk.append((currNode.left, (currSum * 10 ) + currNode.left.data))
return sum
root = Node( 6 )
root.left = Node( 3 )
root.left.left = Node( 2 )
root.left.right = Node( 5 )
root.left.right.left = Node( 7 )
root.left.right.right = Node( 4 )
root.right = Node( 5 )
root.right.right = Node( 4 )
result = treePathsSum(root)
print ( "Sum of numbers formed from root to leaf paths:" , result)
|
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
}
public class GFG {
static long TreePathsSum(Node root)
{
if (root == null )
return 0;
long sum = 0;
Stack<Tuple<Node, long > > stack
= new Stack<Tuple<Node, long > >();
stack.Push( new Tuple<Node, long >(
root,
root.data));
while (stack.Count > 0) {
Node currNode = stack.Peek().Item1;
long currSum = stack.Peek().Item2;
stack.Pop();
if (currNode.left == null
&& currNode.right == null ) {
sum += currSum;
}
else {
if (currNode.right != null ) {
stack.Push( new Tuple<Node, long >(
currNode.right,
(currSum * 10)
+ currNode.right.data));
}
if (currNode.left != null ) {
stack.Push( new Tuple<Node, long >(
currNode.left,
(currSum * 10)
+ currNode.left.data));
}
}
}
return sum;
}
static void Main()
{
Node root = new Node();
root.data = 6;
root.left = new Node();
root.left.data = 3;
root.left.left = new Node();
root.left.left.data = 2;
root.left.right = new Node();
root.left.right.data = 5;
root.left.right.left = new Node();
root.left.right.left.data = 7;
root.left.right.right = new Node();
root.left.right.right.data = 4;
root.right = new Node();
root.right.data = 5;
root.right.right = new Node();
root.right.right.data = 4;
long result = TreePathsSum(root);
Console.WriteLine(
"Sum of numbers formed from root to leaf paths: "
+ result);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function treePathsSum(root) {
if (root === null )
return 0;
let sum = 0;
let stk = [];
stk.push([root, root.data]);
while (stk.length > 0) {
let [currNode, currSum] = stk.pop();
if (currNode.left === null && currNode.right === null ) {
sum += currSum;
}
else {
if (currNode.right !== null ) {
stk.push([currNode.right, (currSum * 10) + currNode.right.data]);
}
if (currNode.left !== null ) {
stk.push([currNode.left, (currSum * 10) + currNode.left.data]);
}
}
}
return sum;
}
let root = new Node(6);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(5);
root.left.right.left = new Node(7);
root.left.right.right = new Node(4);
root.right = new Node(5);
root.right.right = new Node(4);
let result = treePathsSum(root);
console.log( "Sum of numbers formed from root to leaf paths: " + result);
|
Output
Sum of numbers formed from root to leaf paths: 13997
Time Complexity: O(N), where N is the number of nodes in the binary tree. In the worst case, we need to visit each node once.
Auxiliary Space: O(H), where H is the height of the binary tree. In the worst case, the height of the binary tree can be equal to the number of nodes (N), resulting in a space complexity of O(N). This space is used to store the stack during the iterative DFS traversal.
Please Login to comment...