Open In App

Sum of all the numbers that are formed from root to leaf paths

Last Updated : 04 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a binary tree, where every node value is a number. Find the sum of all the numbers that are formed from root to leaf paths.

Examples:

Input:

Sum-of-all-the-numbers-that-are-formed-from-root-to-leaf-paths-48

Output: 13997
Explanation: There are 4 leaves, hence 4 root to leaf paths:

  • 6->3->2 = 632
  • 6->3->5->7 = 6357
  • 6->3->5->4 = 6354
  • 6->5->4 = 654

final answer = 632 + 6357 + 6354 + 654 = 13997

Input:

sum-of-all-the-numbers-that-are-formed-from-root-to-leaf-paths

Output: 2630
Explanation: There are 3 leaves, resulting in leaf path of 1240, 1260, 130 sums to 2630.

The Naive approach to solve this problem is to first find all the paths from the root to the leaf . Then we convert all paths into numbers. In the end, we will add those numbers. Time Complexity of this approach will be O(n^2)  because we are traversing the all the paths and space will be O(n).

[Expected Approach] Using Pre-order traversal - O(n) Time and O(h) Space

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. For every node, we update the value as value*10 plus the node's data. On reaching a leaf node, return the value calculated so far.

C++
// C++ program to find sum of
// all paths from root to leaves 
#include <bits/stdc++.h>
using namespace std;

class Node { 
public:
    int data; 
    Node *left, *right; 
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
}; 

// Function which returns the sum of root to leaf path.
long long treePathsSum(Node* root, long long val = 0) {
    if (root == nullptr) return 0;
    
    // Update value
    val = val*10+root->data;
    
    // If node is leaf node, then
    // return the value.
    if (root->left==nullptr && root->right==nullptr)
        return val;
        
    return treePathsSum(root->left, val) +
    treePathsSum(root->right, val);
}

int main()  { 
    
    // Hard coded binary tree.
    //          6
    //        /  \
    //       3    5
    //     /  \    \
    //    2   5     4  
    //       / \
    //      7   4
    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 << treePathsSum(root) << endl;
    
    return 0; 
} 
C
// C program to find sum of
// all paths from root to leaves
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

// Function which returns the sum of root to leaf path.
long long treePathsSum(struct Node* root, long long val) {
    if (root == NULL) return 0;

    // Update value
    val = val * 10 + root->data;

    // If node is leaf node, then
    // return the value.
    if (root->left == NULL && root->right == NULL)
        return val;

    return treePathsSum(root->left, val) + treePathsSum(root->right, val);
}

struct Node* createNode(int x) {
    struct Node* newNode = 
    	(struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {

    // Hard coded binary tree.
    //          6
    //        /  \
    //       3    5
    //     /  \    \
    //    2   5     4  
    //       / \
    //      7   4
    struct Node* root = createNode(6);
    root->left = createNode(3);
    root->right = createNode(5);
    root->left->left = createNode(2);
    root->left->right = createNode(5);
    root->right->right = createNode(4);
    root->left->right->left = createNode(7);
    root->left->right->right = createNode(4);

    printf("%lld\n", treePathsSum(root, 0));

    return 0;
}
Java
// Java program to find sum of
// all paths from root to leaves
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function which returns the sum of root to leaf path.
    static long treePathsSum(Node root, long val) {
        if (root == null) return 0;

        // Update value
        val = val * 10 + root.data;

        // If node is leaf node, then
        // return the value.
        if (root.left == null && root.right == null)
            return val;

        return treePathsSum(root.left, val) + treePathsSum(root.right, val);
    }

    public static void main(String[] args) {

        // Hard coded binary tree.
        //          6
        //        /  \
        //       3    5
        //     /  \    \
        //    2   5     4  
        //       / \
        //      7   4
        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(treePathsSum(root, 0));
    }
}
Python
# Python program to find sum of
# all paths from root to leaves
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function which returns the sum of root to leaf path.
def treePathsSum(root, val=0):
    if root is None:
        return 0

    # Update value
    val = val * 10 + root.data

    # If node is leaf node, then
    # return the value.
    if root.left is None and root.right is None:
        return val

    return treePathsSum(root.left, val) + treePathsSum(root.right, val)

if __name__ == "__main__":
    
    # Hard coded binary tree.
    #          6
    #        /  \
    #       3    5
    #     /  \    \
    #    2   5     4  
    #       / \
    #      7   4
    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(treePathsSum(root))
C#
// C# program to find sum of
// all paths from root to leaves
using System;

public class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function which returns the sum of root to leaf path.
    static long treePathsSum(Node root, long val = 0) {
        if (root == null) return 0;

        // Update value
        val = val * 10 + root.data;

        // If node is leaf node, then
        // return the value.
        if (root.left == null && root.right == null)
            return val;

        return treePathsSum(root.left, val) + treePathsSum(root.right, val);
    }

    static void Main(string[] args) {

        // Hard coded binary tree.
        //          6
        //        /  \
        //       3    5
        //     /  \    \
        //    2   5     4  
        //       / \
        //      7   4
        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(treePathsSum(root));
    }
}
JavaScript
// JavaScript program to find sum of
// all paths from root to leaves
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function which returns the sum of root to leaf path.
function treePathsSum(root, val = 0) {
    if (root === null) return 0;

    // Update value
    val = val * 10 + root.data;

    // If node is leaf node, then
    // return the value.
    if (root.left === null && root.right === null)
        return val;

    return treePathsSum(root.left, val) 
    		+ treePathsSum(root.right, val);
}

// Hard coded binary tree.
//          6
//        /  \
//       3    5
//     /  \    \
//    2   5     4  
//       / \
//      7   4
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(treePathsSum(root));

Output
13997

[Alternate Approach] Using Iterative Method - O(n) Time and O(h) Space

The 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.

Step by step approach:

  • 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:
    • Pop a node and its corresponding path sum from the stack.
    • If the popped node is a leaf (i.e., it has no left and right children), add the path sum to the overall result.
    • 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.
    • 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 of the above approach:

C++
// C++ program to find sum of
// all paths from root to leaves 
#include <bits/stdc++.h>
using namespace std;

class Node { 
public:
    int data; 
    Node *left, *right; 
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
}; 

// Function which returns the sum of root to leaf path.
int treePathsSum(Node* root) {
    
    // base case
    if (root == nullptr) return 0;
    
    // Store pair of node and value
    // associated with it.
    stack<pair<Node*,int>> st;
    st.push({root, 0});
    
    int ans = 0;
    
    while (!st.empty()) {
        pair<Node*,int> top = st.top();
        st.pop();
        Node* curr = top.first;
        int val = top.second;
        
        // update the value
        val = val*10 + curr->data;
        
        // if current node is leaf node, 
        // then add the value to result.
        if (curr->left == nullptr && curr->right == nullptr) {
            ans += val;  
            continue;
        }
        
        if (curr->right != nullptr) {
            st.push({curr->right, val});
        }
        
        if (curr->left != nullptr) {
            st.push({curr->left, val});
        }
    }
    
    return ans;
}

int main()  { 
    
    // Hard coded binary tree.
    //          6
    //        /  \
    //       3    5
    //     /  \    \
    //    2   5     4  
    //       / \
    //      7   4
    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 << treePathsSum(root) << endl;
    
    return 0; 
} 
Java
// Java program to find sum of
// all paths from root to leaves
import java.util.Stack;
import java.util.AbstractMap;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function which returns the sum of root 
  	// to leaf path.
    static int treePathsSum(Node root) {

        // base case
        if (root == null) return 0;

        // Store pair of node and value
        // associated with it.
        Stack<AbstractMap.SimpleEntry<Node, Integer>> st = 
          								new Stack<>();
        st.push(new AbstractMap.SimpleEntry<>(root, 0));

        int ans = 0;

        while (!st.isEmpty()) {
            AbstractMap.SimpleEntry<Node, Integer> top = st.pop();
            Node curr = top.getKey();
            int val = top.getValue();

            // update the value
            val = val * 10 + curr.data;

            // if current node is leaf node, 
            // then add the value to result.
            if (curr.left == null && curr.right == null) {
                ans += val;
                continue;
            }

            if (curr.right != null) {
                st.push(new AbstractMap.SimpleEntry<>
                        			(curr.right, val));
            }

            if (curr.left != null) {
                st.push(new AbstractMap.SimpleEntry<>
                        			(curr.left, val));
            }
        }

        return ans;
    }

    public static void main(String[] args) {

        // Hard coded binary tree.
        //          6
        //        /  \
        //       3    5
        //     /  \    \
        //    2   5     4  
        //       / \
        //      7   4
        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(treePathsSum(root));
    }
}
Python
# Python program to find sum of
# all paths from root to leaves

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function which returns the sum of root
# to leaf path.
def treePathsSum(root):

    # base case
    if root is None:
        return 0

    # Store pair of node and value
    # associated with it.
    st = [(root, 0)]

    ans = 0

    while st:
        curr, val = st.pop()

        # update the value
        val = val * 10 + curr.data

        # if current node is leaf node,
        # then add the value to result.
        if curr.left is None and curr.right is None:
            ans += val
            continue

        if curr.right is not None:
            st.append((curr.right, val))

        if curr.left is not None:
            st.append((curr.left, val))

    return ans

if __name__ == "__main__":

    # Hard coded binary tree.
    #          6
    #        /  \
    #       3    5
    #     /  \    \
    #    2   5     4  
    #       / \
    #      7   4
    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(treePathsSum(root))
C#
// C# program to find sum of
// all paths from root to leaves
using System;
using System.Collections.Generic;

public class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function which returns the sum of root to
  	// leaf path.
    static int treePathsSum(Node root) {

        // base case
        if (root == null) return 0;

        // Store pair of node and value
        // associated with it.
        Stack<KeyValuePair<Node, int>> st = new 
          						Stack<KeyValuePair<Node, int>>();
        st.Push(new KeyValuePair<Node, int>(root, 0));

        int ans = 0;

        while (st.Count > 0) {
            var top = st.Pop();
            Node curr = top.Key;
            int val = top.Value;

            // update the value
            val = val * 10 + curr.data;

            // if current node is leaf node,
            // then add the value to result.
            if (curr.left == null && curr.right == null) {
                ans += val;
                continue;
            }

            if (curr.right != null) {
                st.Push(new KeyValuePair<Node, 
                        int>(curr.right, val));
            }

            if (curr.left != null) {
                st.Push(new KeyValuePair<Node,
                        int>(curr.left, val));
            }
        }

        return ans;
    }

    static void Main(string[] args) {

        // Hard coded binary tree.
        //          6
        //        /  \
        //       3    5
        //     /  \    \
        //    2   5     4  
        //       / \
        //      7   4
        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(treePathsSum(root));
    }
}
JavaScript
// JavaScript program to find sum of
// all paths from root to leaves

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function which returns the sum of root to leaf path.
function treePathsSum(root) {

    // base case
    if (root === null) return 0;

    // Store pair of node and value
    // associated with it.
    let st = [[root, 0]];

    let ans = 0;

    while (st.length > 0) {
        let [curr, val] = st.pop();

        // update the value
        val = val * 10 + curr.data;

        // if current node is leaf node,
        // then add the value to result.
        if (curr.left === null && curr.right === null) {
            ans += val;
            continue;
        }

        if (curr.right !== null) {
            st.push([curr.right, val]);
        }

        if (curr.left !== null) {
            st.push([curr.left, val]);
        }
    }

    return ans;
}

// Hard coded binary tree.
//          6
//        /  \
//       3    5
//     /  \    \
//    2   5     4  
//       / \
//      7   4
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(treePathsSum(root));

Output
13997

Sum of all the numbers formed from root to leaf paths
Article Tags :
Practice Tags :

Similar Reads