Given the root of a binary tree where each node contains a single digit (0–9).
- Every root-to-leaf path represents a number formed by concatenating the digits along the path.
- Starting from the root, each next digit is appended to the current number (i.e., currentNumber = currentNumber * 10 + node->data).
- Return the sum of all the numbers formed by every root-to-leaf path.
Examples:
Input:
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:
Output: 222
Explanation: There are 3 leaves, resulting in leaf path of 103, 100, 19 sums to 222.
Table of Content
[Naive Approach] Generate All Paths - O(n^2) Time and O(n) Space
The idea is to traverse the binary tree and store the digits of the current root-to-leaf path. Whenever a leaf node is reached, convert the stored digits into a number and add it to the total sum.
Working of the Approach:
- Start DFS traversal from the root and maintain the digits of the current path.
- Add each visited node's digit to the current path.
- When a leaf node is reached, construct the number represented by the stored digits.
- Add this number to the total sum.
- Backtrack by removing the current node's digit before exploring another path.
- Return the sum of all root-to-leaf numbers.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
long long calculateNumber(vector<int>& path) {
long long num = 0;
for (int digit : path)
num = num * 10 + digit;
return num;
}
void dfs(Node* root, vector<int>& path, long long& sum) {
if (root == nullptr)
return;
path.push_back(root->data);
if (root->left == nullptr && root->right == nullptr) {
// Convert the root-to-leaf path into a number.
sum += calculateNumber(path);
}
dfs(root->left, path, sum);
dfs(root->right, path, sum);
path.pop_back();
}
long long treePathsSum(Node* root) {
vector<int> path;
long long sum = 0;
dfs(root, path, sum);
return sum;
}
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 << treePathsSum(root) << endl;
return 0;
}
import java.util.ArrayList;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GFG {
static long calculateNumber(ArrayList<Integer> path) {
long num = 0;
for (int digit : path)
num = num * 10 + digit;
return num;
}
static void dfs(Node root, ArrayList<Integer> path, long[] sum) {
if (root == null)
return;
path.add(root.data);
if (root.left == null && root.right == null) {
// Convert the root-to-leaf path into a number.
sum[0] += calculateNumber(path);
}
dfs(root.left, path, sum);
dfs(root.right, path, sum);
path.remove(path.size() - 1);
}
static long treePathsSum(Node root) {
ArrayList<Integer> path = new ArrayList<>();
long[] sum = {0};
dfs(root, path, sum);
return sum[0];
}
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(treePathsSum(root));
}
}
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def calculateNumber(path):
num = 0
for digit in path:
num = num * 10 + digit
return num
def dfs(root, path):
if root is None:
return 0
path.append(root.data)
if root.left is None and root.right is None:
# Convert the root-to-leaf path into a number.
total = calculateNumber(path)
else:
total = dfs(root.left, path) + dfs(root.right, path)
path.pop()
return total
def treePathsSum(root):
return dfs(root, [])
if __name__ == "__main__":
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))
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node(int val)
{
data = val;
left = right = null;
}
}
class GFG
{
static long calculateNumber(List<int> path)
{
long num = 0;
foreach (int digit in path)
num = num * 10 + digit;
return num;
}
static long dfs(Node root, List<int> path)
{
if (root == null)
return 0;
path.Add(root.data);
long sum;
if (root.left == null && root.right == null)
{
// Convert the root-to-leaf path into a number.
sum = calculateNumber(path);
}
else
{
sum = dfs(root.left, path) + dfs(root.right, path);
}
path.RemoveAt(path.Count - 1);
return sum;
}
static long treePathsSum(Node root)
{
return dfs(root, new List<int>());
}
static void 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);
Console.WriteLine(treePathsSum(root));
}
}
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function calculateNumber(path) {
let num = 0;
for (let digit of path)
num = num * 10 + digit;
return num;
}
function dfs(root, path, sum) {
if (root === null)
return sum;
path.push(root.data);
if (root.left === null && root.right === null) {
// Convert the root-to-leaf path into a number.
sum += calculateNumber(path);
} else {
sum = dfs(root.left, path, sum);
sum = dfs(root.right, path, sum);
}
path.pop();
return sum;
}
function treePathsSum(root) {
return dfs(root, [], 0);
}
// Driver Code
const 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
[Expected Approach] Use DFS - O(n) Time and O(h) Space
The idea is to construct the number represented by each root-to-leaf path while performing a DFS traversal.
As we move down the tree using currentNumber = currentNumber * 10 + node->data.
Working of the Approach:
- Start DFS from the root with currentNumber = 0.
- For each node, update the current number as currentNumber * 10 + node->data.
- Continue the DFS for the left and right children.
- When a leaf node is reached, add the current number to the total sum.
- Return the sum obtained after traversing the entire tree.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
long long treePathsSum(Node* root, long long val = 0) {
if (root == nullptr)
return 0;
// Update the number formed by the current path.
val = val * 10 + root->data;
if (root->left == nullptr && root->right == nullptr)
return val;
return treePathsSum(root->left, val) +
treePathsSum(root->right, val);
}
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 << treePathsSum(root) << endl;
return 0;
}
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GFG {
static int dfs(Node root, int val) {
if (root == null)
return 0;
// Update the number formed by the current path.
val = val * 10 + root.data;
if (root.left == null && root.right == null)
return val;
return dfs(root.left, val) + dfs(root.right, val);
}
static int treePathsSum(Node root) {
return dfs(root, 0);
}
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(treePathsSum(root));
}
}
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def treePathsSum(root, val=0):
if root is None:
return 0
# Update the number formed by the current path.
val = val * 10 + root.data
if root.left is None and root.right is None:
return val
return treePathsSum(root.left, val) + treePathsSum(root.right, val)
if __name__ == "__main__":
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))
using System;
class Node
{
public int data;
public Node left;
public Node right;
public Node(int val)
{
data = val;
left = right = null;
}
}
class GFG
{
static long treePathsSum(Node root, long val = 0)
{
if (root == null)
return 0;
// Update the number formed by the current path.
val = val * 10 + root.data;
if (root.left == null && root.right == null)
return val;
return treePathsSum(root.left, val) +
treePathsSum(root.right, val);
}
static void 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);
Console.WriteLine(treePathsSum(root));
}
}
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
function treePathsSum(root, val = 0) {
if (root === null)
return 0;
// Update the number formed by the current path.
val = val * 10 + root.data;
if (root.left === null && root.right === null)
return val;
return treePathsSum(root.left, val) +
treePathsSum(root.right, val);
}
// Driver Code
const 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

Output: