Open in App
Not now

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

• Difficulty Level : Medium
• Last Updated : 23 Feb, 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 ```
Recommended Practice

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++

 `// C++ program to find sum of` `// all paths from root to leaves ` `#include ` `using` `namespace` `std;`   `class` `node ` `{ ` `    ``public``:` `    ``int` `data; ` `    ``node *left, *right; ` `}; `   `// function to allocate new node with given data ` `node* newNode(``int` `data) ` `{ ` `    ``node* Node = ``new` `node();` `    ``Node->data = data; ` `    ``Node->left = Node->right = NULL; ` `    ``return` `(Node); ` `} `   `// 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 ` `int` `treePathsSumUtil(node *root, ``int` `val) ` `{ ` `    ``// Base case ` `    ``if` `(root == NULL) ``return` `0; `   `    ``// Update val ` `    ``val = (val*10 + root->data); `   `    ``// if current node is leaf, return the current value of val ` `    ``if` `(root->left==NULL && root->right==NULL) ` `    ``return` `val; `   `    ``// recur sum of values for left and right subtree ` `    ``return` `treePathsSumUtil(root->left, val) + ` `        ``treePathsSumUtil(root->right, val); ` `} `   `// A wrapper function over treePathsSumUtil() ` `int` `treePathsSum(node *root) ` `{ ` `    ``// Pass the initial value as 0` `    ``// as there is nothing above root ` `    ``return` `treePathsSumUtil(root, 0); ` `} `   `// Driver code` `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 "``<

## C

 `// C program to find sum of all paths from root to leaves` `#include ` `#include `   `struct` `node` `{` `    ``int` `data;` `    ``struct` `node *left, *right;` `};`   `// function to allocate new node with given data` `struct` `node* newNode(``int` `data)` `{` `    ``struct` `node* node = (``struct` `node*)``malloc``(``sizeof``(``struct` `node));` `    ``node->data = data;` `    ``node->left = node->right = NULL;` `    ``return` `(node);` `}`   `// 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` `int` `treePathsSumUtil(``struct` `node *root, ``int` `val)` `{` `    ``// Base case` `    ``if` `(root == NULL)  ``return` `0;`   `    ``// Update val` `    ``val = (val*10 + root->data);`   `    ``// if current node is leaf, return the current value of val` `    ``if` `(root->left==NULL && root->right==NULL)` `       ``return` `val;`   `    ``// recur sum of values for left and right subtree` `    ``return` `treePathsSumUtil(root->left, val) +` `           ``treePathsSumUtil(root->right, val);` `}`   `// A wrapper function over treePathsSumUtil()` `int` `treePathsSum(``struct` `node *root)` `{` `    ``// Pass the initial value as 0 as there is nothing above root` `    ``return` `treePathsSumUtil(root, 0);` `}`   `// Driver function to test the above functions` `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

 `// Java program to find sum of all numbers that are formed from root` `// to leaf paths` ` `  `// A binary tree node` `class` `Node ` `{` `    ``int` `data;` `    ``Node left, right;` `     `  `    ``Node(``int` `item) ` `    ``{` `        ``data = item;` `        ``left = right = ``null``;` `    ``}` `}` ` `  `class` `BinaryTree ` `{` `    ``Node root;` ` `  `    ``// 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` `    ``int` `treePathsSumUtil(Node node, ``int` `val) ` `    ``{` `        ``// Base case` `        ``if` `(node == ``null``)` `            ``return` `0``;` ` `  `        ``// Update val` `        ``val = (val * ``10` `+ node.data);` ` `  `        ``// if current node is leaf, return the current value of val` `        ``if` `(node.left == ``null` `&& node.right == ``null``)` `            ``return` `val;` ` `  `        ``// recur sum of values for left and right subtree` `        ``return` `treePathsSumUtil(node.left, val)` `                ``+ treePathsSumUtil(node.right, val);` `    ``}` ` `  `    ``// A wrapper function over treePathsSumUtil()` `    ``int` `treePathsSum(Node node) ` `    ``{` `        ``// Pass the initial value as 0 as there is nothing above root` `        ``return` `treePathsSumUtil(node, ``0``);` `    ``}` ` `  `    ``// Driver program to test above functions` `    ``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));   ` `    ``}    ` `}` ` `  `// This code has been contributed by Mayank Jaiswal`

## Python3

 `# Python program to find sum of all paths from root to leaves`   `# A Binary tree node` `class` `Node:`   `    ``# Constructor to create a new node` `    ``def` `__init__(``self``, data):` `        ``self``.data ``=` `data` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `# Returns sums of all root to leaf paths. The first parameter is root` `# of current subtree, the second paramete"r is value of the number` `# formed by nodes from root to this node` `def` `treePathsSumUtil(root, val):`   `    ``# Base Case` `    ``if` `root ``is` `None``:` `        ``return` `0`   `    ``# Update val` `    ``val ``=` `(val``*``10` `+` `root.data)`   `    ``# If current node is leaf, return the current value of val` `    ``if` `root.left ``is` `None` `and` `root.right ``is` `None``:` `        ``return` `val`   `    ``# Recur sum of values for left and right subtree` `    ``return` `(treePathsSumUtil(root.left, val) ``+` `            ``treePathsSumUtil(root.right, val))`   `# A wrapper function over treePathSumUtil()` `def` `treePathsSum(root):` `    `  `    ``# Pass the initial value as 0 as there is nothing above root` `    ``return` `treePathsSumUtil(root, ``0``)`   `# Driver function to test above function` `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))`   `# This code is contributed by Nikhil Kumar Singh(nickzuck_007)`

## C#

 `// c# program to find sum of all numbers ` `// that are formed from root to leaf paths ` `using` `System;`   `// A binary tree node ` `public` `class` `Node` `{` `    ``public` `int` `data;` `    ``public` `Node left, right;`   `    ``public` `Node(``int` `item)` `    ``{` `        ``data = item;` `        ``left = right = ``null``;` `    ``}` `}`   `class` `GFG` `{` `public` `Node root;`   `// 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 ` `public` `virtual` `int` `treePathsSumUtil(Node node,` `                                    ``int` `val)` `{` `    ``// Base case ` `    ``if` `(node == ``null``)` `    ``{` `        ``return` `0;` `    ``}`   `    ``// Update val ` `    ``val = (val * 10 + node.data);`   `    ``// if current node is leaf, return ` `    ``// the current value of val ` `    ``if` `(node.left == ``null` `&& node.right == ``null``)` `    ``{` `        ``return` `val;` `    ``}`   `    ``// recur sum of values for left and right subtree ` `    ``return` `treePathsSumUtil(node.left, val) +` `           ``treePathsSumUtil(node.right, val);` `}`   `// A wrapper function over treePathsSumUtil() ` `public` `virtual` `int` `treePathsSum(Node node)` `{` `    ``// Pass the initial value as 0 as ` `    ``// there is nothing above root ` `    ``return` `treePathsSumUtil(node, 0);` `}`   `// Driver Code` `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));` `}` `}`   `// This code is contributed by Shrikant13`

## Javascript

 ``

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++

 `// C++ program to find sum of all paths from root to leaves`   `// A Binary tree node` `#include ` `using` `namespace` `std;`   `// A Binary tree node` `class` `Node ` `{ ` `    ``public``:` `    ``int` `data; ` `    ``Node *left, *right; ` `  `  `    ``// Constructor to create a new node` `      ``Node(``int` `val)` `    ``{` `      ``data = val;` `      ``left = right = NULL; ` `    ``}` `}; `   `void` `treePathsSumUtil(Node* root, vector currPath, ` `                      ``vector> &allPath)` `{` `    ``// Base Case` `    ``if` `(root == NULL)` `        ``return``;`   `    ``// append the root data in string format in currPath` `    ``currPath.push_back((to_string)(root->data));`   `    ``// if we found a leaf node we copy the currPath to allPath` `    ``if` `(root->left == NULL && root->right == NULL)` `        ``allPath.push_back(currPath);`   `    ``// traverse in the left subtree` `    ``treePathsSumUtil(root->left, currPath, allPath);`   `    ``// traverse in the right subtree` `    ``treePathsSumUtil(root->right, currPath, allPath);`   `    ``// remove the current element from the path` `    ``currPath.pop_back();` `}` `int` `treePathsSum(Node* root)` `{` `  `  `    ``// store all the root to leaf path in allPath` `    ``vector> allPath;` `    ``vector v;` `    ``treePathsSumUtil(root, v, allPath);` `  `  `    ``// store the sum` `    ``int` `s = 0;`   `    ``for``(``auto` `pathNumber : allPath)` `    ``{` `        ``string k=``""``;` `      `  `        ``// join the pathNumbers to convert them  ` `      ``// into the number to calculate sum` `        ``for``(``auto` `x: pathNumber)` `            ``k = k+x;` `        ``s += stoi(k);` `    ``}` `    ``return` `s;` `}` ` `  `// Driver code` `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 "``<

## Java

 `// Java program to find sum of all paths from root to leaves` `import` `java.util.*;`   `public` `class` `GFG {`   `  ``// A Binary tree node` `  ``static` `class` `Node {` `    ``int` `data;` `    ``Node left, right;`   `    ``// Constructor to create a new node` `    ``Node(``int` `val)` `    ``{` `      ``data = val;` `      ``left = right = ``null``;` `    ``}` `  ``};`   `  ``static` `void` `    ``treePathsSumUtil(Node root, ArrayList currPath,` `                     ``ArrayList > allPath)` `  ``{` `    ``// Base Case` `    ``if` `(root == ``null``)` `      ``return``;`   `    ``// append the root data in string format in currPath` `    ``currPath.add((``""` `+ root.data));`   `    ``// if we found a leaf node we copy the currPath to` `    ``// allPath` `    ``if` `(root.left == ``null` `&& root.right == ``null``)` `      ``allPath.add(``new` `ArrayList<>(currPath));`   `    ``// traverse in the left subtree` `    ``treePathsSumUtil(root.left, currPath, allPath);`   `    ``// traverse in the right subtree` `    ``treePathsSumUtil(root.right, currPath, allPath);`   `    ``// remove the current element from the path` `    ``currPath.remove(currPath.size() - ``1``);` `  ``}` `  ``static` `int` `treePathsSum(Node root)` `  ``{`   `    ``// store all the root to leaf path in allPath` `    ``ArrayList > allPath` `      ``= ``new` `ArrayList<>();` `    ``ArrayList v = ``new` `ArrayList<>();` `    ``treePathsSumUtil(root, v, allPath);`   `    ``// store the sum` `    ``int` `s = ``0``;`   `    ``for` `(ArrayList pathNumber : allPath) {` `      ``String k = ``""``;`   `      ``// join the pathNumbers to convert them` `      ``// into the number to calculate sum` `      ``for` `(String x : pathNumber)` `        ``k += x;` `      ``s += Integer.parseInt(k);` `    ``}` `    ``return` `s;` `  ``}`   `  ``// Driver code` `  ``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));` `  ``}` `}`   `// This code is contributed by Karandeep1234`

## Python3

 `# Python program to find sum of all paths from root to leaves`   `# A Binary tree node`     `class` `Node:`   `    ``# Constructor to create a new node` `    ``def` `__init__(``self``, data):` `        ``self``.data ``=` `data` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`     `def` `treePathsSumUtil(root, currPath, allPath):` `  `  `    ``# Base Case` `    ``if` `root ``is` `None``:` `        ``return`   `    ``# append the root data in string format in currPath` `    ``currPath.append(``str``(root.data))`   `    ``# if we found a leaf node we copy the currPath to allPath` `    ``if` `root.left ``is` `None` `and` `root.right ``is` `None``:` `        ``allPath.append(currPath.copy())`   `    ``# traverse in the left subtree` `    ``treePathsSumUtil(root.left, currPath, allPath)`   `    ``# traverse in the right subtree` `    ``treePathsSumUtil(root.right, currPath, allPath)`   `    ``# remove the current element from the path` `    ``del` `currPath[``-``1``]`     `def` `treePathsSum(root):` `    ``# store all the root to leaf path in allPath` `    ``allPath ``=` `[]`   `    ``treePathsSumUtil(root, [], allPath)` `    ``# store the sum` `    ``s ``=` `0`   `    ``for` `pathNumber ``in` `allPath:` `        ``# join the pathNumbers to convert them  into the number to calculate sum` `        ``k ``=` `"".join(pathNumber)` `        ``s ``+``=` `int``(k)` `    ``return` `s`     `# Driver function to test above function` `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))`   `# this code is contributed by Vivek Maddeshiya`

## C#

 `//C# code for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{` `    ``// A Binary tree node` `    ``class` `Node` `    ``{` `        ``public` `int` `data;` `        ``public` `Node left, right;`   `        ``// Constructor to create a new node` `        ``public` `Node(``int` `val)` `        ``{` `            ``data = val;` `            ``left = right = ``null``;` `        ``}` `    ``}` `    ``static` `void` `treePathsSumUtil(Node root, List<``string``> currPath, List> allPath)` `    ``{` `        ``// Base Case` `        ``if` `(root == ``null``)` `            ``return``;`   `        ``// append the root data in string format in currPath` `        ``currPath.Add(root.data.ToString());`   `        ``// if we found a leaf node we copy the currPath to` `        ``// allPath` `        ``if` `(root.left == ``null` `&& root.right == ``null``)` `            ``allPath.Add(``new` `List<``string``>(currPath));`   `        ``// traverse in the left subtree` `        ``treePathsSumUtil(root.left, currPath, allPath);`   `        ``// traverse in the right subtree` `        ``treePathsSumUtil(root.right, currPath, allPath);`   `        ``// remove the current element from the path` `        ``currPath.RemoveAt(currPath.Count - 1);` `    ``}`   `    ``static` `int` `treePathsSum(Node root)` `    ``{`   `        ``// store all the root to leaf path in allPath` `        ``List> allPath = ``new` `List>();` `        ``List<``string``> v = ``new` `List<``string``>();` `        ``treePathsSumUtil(root, v, allPath);`   `        ``// store the sum` `        ``int` `s = 0;`   `        ``foreach` `(List<``string``> pathNumber ``in` `allPath)` `        ``{` `            ``string` `k = ``""``;`   `            ``// join the pathNumbers to convert them` `            ``// into the number to calculate sum` `            ``foreach` `(``string` `x ``in` `pathNumber)` `                ``k += x;` `            ``s += ``int``.Parse(k);` `        ``}` `        ``return` `s;` `    ``}`   `    ``// Driver code` `    ``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

 `// JavaScript program to find sum of all paths from root to leaves`   `// A Binary tree node` `class Node {` `    ``// Constructor to create a new node` `    ``constructor(data) {` `        ``this``.data = data;` `        ``this``.left = ``null``;` `        ``this``.right = ``null``;` `    ``}` `}`   `function` `treePathsSumUtil(root, currPath, allPath) {` `    ``// Base Case` `    ``if` `(root === ``null``) {` `        ``return``;` `    ``}`   `    ``// append the root data in string format in currPath` `    ``currPath.push(String(root.data));`   `    ``// if we found a leaf node we copy the currPath to allPath` `    ``if` `(root.left === ``null` `&& root.right === ``null``) {` `        ``allPath.push(currPath.slice());` `    ``}`   `    ``// traverse in the left subtree` `    ``treePathsSumUtil(root.left, currPath, allPath);`   `    ``// traverse in the right subtree` `    ``treePathsSumUtil(root.right, currPath, allPath);`   `    ``// remove the current element from the path` `    ``currPath.pop();` `}`   `function` `treePathsSum(root) {` `    ``// store all the root to leaf path in allPath` `    ``let allPath = [];`   `    ``treePathsSumUtil(root, [], allPath);` `    ``// store the sum` `    ``let s = 0;`   `    ``for` `(const pathNumber of allPath) {` `        ``// join the pathNumbers to convert them into the number to calculate sum` `        ``let k = pathNumber.join(``""``);` `        ``s += Number(k);` `    ``}` `    ``return` `s;` `}`   `// Driver function to test above function` `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));`   `// This code is contributed by adityamaharshi21`

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)

My Personal Notes arrow_drop_up
Related Articles