Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree.
Examples:
Input:
30
/ \
10 50
/ \ / \
3 16 40 60
Output: 43 56 120 140
Explanation:
In the above binary tree
there are 4 leaf nodes.
Hence, total 4 path sum are
present from root node to the
leaf node.
(i.e., 30-10-3, 30-10-16,
30-50-40, 30-50-60)
Therefore, the path sums from
left to right would be
(43, 56, 120, 140).
Input:
11
/ \
12 5
\ /
16 40
Output: 39 56
Explanation:
In the above binary tree
there are 2 leaf nodes.
Hence, total 2 path sum are
present from root node to
the leaf node.
(i.e 11-12-16, 11-5-40)
Therefore, the path sums from
left to right would be (39 56).
Approach: The idea is to use DFS Traversal to travel from the root to the leaf of the binary tree and calculate the sum of each root to leaf path. Follow the steps below to solve the problem:
- Start from the root node of the Binary tree with the initial path sum of 0.
- Add the value of the current node to the path sum.
- Travel to the left and right child of the current node with the present value of the path sum.
- Repeat Step 2 and 3 for all the subsequent nodes of the binary tree.
- On reaching the leaf node, add the path sum to the vector of pathSum.
- Print all the elements of the vector pathSum as the output.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
};
struct TreeNode* addNode( int data)
{
struct TreeNode* node
= ( struct TreeNode*) malloc (
sizeof ( struct TreeNode));
node->val = data;
node->left = NULL;
node->right = NULL;
return node;
};
void dfs(TreeNode* root, int sum,
vector< int >& pathSum)
{
if (root == NULL)
return ;
sum += root->val;
if (root->left == NULL
and root->right == NULL) {
pathSum.push_back(sum);
return ;
}
dfs(root->left, sum, pathSum);
dfs(root->right, sum, pathSum);
}
void findPathSum(TreeNode* root)
{
vector< int > pathSum;
dfs(root, 0, pathSum);
for ( int num : pathSum) {
cout << num << " " ;
}
cout << endl;
}
int main()
{
TreeNode* root = addNode(30);
root->left = addNode(10);
root->right = addNode(50);
root->left->left = addNode(3);
root->left->right = addNode(16);
root->right->left = addNode(40);
root->right->right = addNode(60);
findPathSum(root);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node
{
int val;
Node left, right;
};
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = temp.right = null ;
return temp;
}
static void dfs(Node root, int sum,
ArrayList<Integer> pathSum)
{
if (root == null )
return ;
sum += root.val;
if (root.left == null &&
root.right == null )
{
pathSum.add(sum);
return ;
}
dfs(root.left, sum, pathSum);
dfs(root.right, sum, pathSum);
}
static void findPathSum(Node root)
{
ArrayList<Integer> pathSum = new ArrayList<>();
dfs(root, 0 , pathSum);
for ( int num : pathSum)
{
System.out.print(num + " " );
}
}
public static void main(String[] args)
{
Node root = newNode( 30 );
root.left = newNode( 10 );
root.right = newNode( 50 );
root.left.left = newNode( 3 );
root.left.right = newNode( 16 );
root.right.left = newNode( 40 );
root.right.right = newNode( 60 );
findPathSum(root);
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , x):
self .data = x
self .left = None
self .right = None
pathSum = []
def dfs(root, sum ):
if (root = = None ):
return
sum + = root.data
if (root.left = = None and
root.right = = None ):
pathSum.append( sum )
return
dfs(root.left, sum )
dfs(root.right, sum )
def findPathSum(root):
dfs(root, 0 )
for num in pathSum:
print (num, end = " " )
if __name__ = = '__main__' :
root = Node( 30 )
root.left = Node( 10 )
root.right = Node( 50 )
root.left.left = Node( 3 )
root.left.right = Node( 16 )
root.right.left = Node( 40 )
root.right.right = Node( 60 )
findPathSum(root)
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int val;
public Node left, right;
public Node( int item)
{
val = item;
left = right = null ;
}
}
public class BinaryTree
{
public static Node node;
static void dfs(Node root, int sum, List< int > pathSum)
{
if (root == null )
{
return ;
}
sum += root.val;
if (root.left == null && root.right == null )
{
pathSum.Add(sum);
return ;
}
dfs(root.left, sum, pathSum);
dfs(root.right, sum, pathSum);
}
static void findPathSum(Node root)
{
List< int > pathSum = new List< int >();
dfs(root, 0, pathSum);
foreach ( int num in pathSum)
{
Console.Write(num + " " );
}
}
static public void Main ()
{
BinaryTree.node = new Node(30);
BinaryTree.node.left = new Node(10);
BinaryTree.node.right = new Node(50);
BinaryTree.node.left.left = new Node(3);
BinaryTree.node.left.right = new Node(16);
BinaryTree.node.right.left = new Node(40);
BinaryTree.node.right.right = new Node(60);
findPathSum(node);
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .val=data;
this .left= this .right= null ;
}
}
function dfs(root,sum,pathSum)
{
if (root == null )
return ;
sum += root.val;
if (root.left == null &&
root.right == null )
{
pathSum.push(sum);
return ;
}
dfs(root.left, sum, pathSum);
dfs(root.right, sum, pathSum);
}
function findPathSum(root)
{
let pathSum = [];
dfs(root, 0, pathSum);
for (let num=0;num<pathSum.length;num++)
{
document.write(pathSum[num] + " " );
}
}
let root = new Node(30);
root.left = new Node(10);
root.right = new Node(50);
root.left.left = new Node(3);
root.left.right = new Node(16);
root.right.left = new Node(40);
root.right.right = new Node(60);
findPathSum(root);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
17 Jun, 2021
Like Article
Save Article