Sum of all the numbers that are formed from root to leaf paths
Last Updated :
04 Nov, 2024
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:
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: 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));
[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));
Sum of all the numbers formed from root to leaf paths
Similar Reads
Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina
15+ min read
Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina
4 min read
Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has
11 min read
Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The
8 min read
Deletion in a Binary Tree Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Types of Binary Tree