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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function which returns the sum of root to leaf path.longlongtreePathsSum(Node*root,longlongval=0){if(root==nullptr)return0;// Update valueval=val*10+root->data;// If node is leaf node, then// return the value.if(root->left==nullptr&&root->right==nullptr)returnval;returntreePathsSum(root->left,val)+treePathsSum(root->right,val);}intmain(){// Hard coded binary tree.// 6// / \ // 3 5// / \ \ // 2 5 4 // / \ // 7 4Node*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<<treePathsSum(root)<<endl;return0;}
C
// C program to find sum of// all paths from root to leaves#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left,*right;};// Function which returns the sum of root to leaf path.longlongtreePathsSum(structNode*root,longlongval){if(root==NULL)return0;// Update valueval=val*10+root->data;// If node is leaf node, then// return the value.if(root->left==NULL&&root->right==NULL)returnval;returntreePathsSum(root->left,val)+treePathsSum(root->right,val);}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// Hard coded binary tree.// 6// / \ // 3 5// / \ \ // 2 5 4 // / \ // 7 4structNode*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));return0;}
Java
// Java program to find sum of// all paths from root to leavesclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function which returns the sum of root to leaf path.staticlongtreePathsSum(Noderoot,longval){if(root==null)return0;// Update valueval=val*10+root.data;// If node is leaf node, then// return the value.if(root.left==null&&root.right==null)returnval;returntreePathsSum(root.left,val)+treePathsSum(root.right,val);}publicstaticvoidmain(String[]args){// Hard coded binary tree.// 6// / \// 3 5// / \ \// 2 5 4 // / \// 7 4Noderoot=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);System.out.println(treePathsSum(root,0));}}
Python
# Python program to find sum of# all paths from root to leavesclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function which returns the sum of root to leaf path.deftreePathsSum(root,val=0):ifrootisNone:return0# Update valueval=val*10+root.data# If node is leaf node, then# return the value.ifroot.leftisNoneandroot.rightisNone:returnvalreturntreePathsSum(root.left,val)+treePathsSum(root.right,val)if__name__=="__main__":# Hard coded binary tree.# 6# / \# 3 5# / \ \# 2 5 4 # / \# 7 4root=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 leavesusingSystem;publicclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function which returns the sum of root to leaf path.staticlongtreePathsSum(Noderoot,longval=0){if(root==null)return0;// Update valueval=val*10+root.data;// If node is leaf node, then// return the value.if(root.left==null&&root.right==null)returnval;returntreePathsSum(root.left,val)+treePathsSum(root.right,val);}staticvoidMain(string[]args){// Hard coded binary tree.// 6// / \// 3 5// / \ \// 2 5 4 // / \// 7 4Noderoot=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);Console.WriteLine(treePathsSum(root));}}
JavaScript
// JavaScript program to find sum of// all paths from root to leavesclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function which returns the sum of root to leaf path.functiontreePathsSum(root,val=0){if(root===null)return0;// Update valueval=val*10+root.data;// If node is leaf node, then// return the value.if(root.left===null&&root.right===null)returnval;returntreePathsSum(root.left,val)+treePathsSum(root.right,val);}// Hard coded binary tree.// 6// / \// 3 5// / \ \// 2 5 4 // / \// 7 4letroot=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);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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function which returns the sum of root to leaf path.inttreePathsSum(Node*root){// base caseif(root==nullptr)return0;// Store pair of node and value// associated with it.stack<pair<Node*,int>>st;st.push({root,0});intans=0;while(!st.empty()){pair<Node*,int>top=st.top();st.pop();Node*curr=top.first;intval=top.second;// update the valueval=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});}}returnans;}intmain(){// Hard coded binary tree.// 6// / \ // 3 5// / \ \ // 2 5 4 // / \ // 7 4Node*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<<treePathsSum(root)<<endl;return0;}
Java
// Java program to find sum of// all paths from root to leavesimportjava.util.Stack;importjava.util.AbstractMap;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function which returns the sum of root // to leaf path.staticinttreePathsSum(Noderoot){// base caseif(root==null)return0;// Store pair of node and value// associated with it.Stack<AbstractMap.SimpleEntry<Node,Integer>>st=newStack<>();st.push(newAbstractMap.SimpleEntry<>(root,0));intans=0;while(!st.isEmpty()){AbstractMap.SimpleEntry<Node,Integer>top=st.pop();Nodecurr=top.getKey();intval=top.getValue();// update the valueval=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(newAbstractMap.SimpleEntry<>(curr.right,val));}if(curr.left!=null){st.push(newAbstractMap.SimpleEntry<>(curr.left,val));}}returnans;}publicstaticvoidmain(String[]args){// Hard coded binary tree.// 6// / \// 3 5// / \ \// 2 5 4 // / \// 7 4Noderoot=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);System.out.println(treePathsSum(root));}}
Python
# Python program to find sum of# all paths from root to leavesclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function which returns the sum of root# to leaf path.deftreePathsSum(root):# base caseifrootisNone:return0# Store pair of node and value# associated with it.st=[(root,0)]ans=0whilest:curr,val=st.pop()# update the valueval=val*10+curr.data# if current node is leaf node,# then add the value to result.ifcurr.leftisNoneandcurr.rightisNone:ans+=valcontinueifcurr.rightisnotNone:st.append((curr.right,val))ifcurr.leftisnotNone:st.append((curr.left,val))returnansif__name__=="__main__":# Hard coded binary tree.# 6# / \# 3 5# / \ \# 2 5 4 # / \# 7 4root=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 leavesusingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function which returns the sum of root to// leaf path.staticinttreePathsSum(Noderoot){// base caseif(root==null)return0;// Store pair of node and value// associated with it.Stack<KeyValuePair<Node,int>>st=newStack<KeyValuePair<Node,int>>();st.Push(newKeyValuePair<Node,int>(root,0));intans=0;while(st.Count>0){vartop=st.Pop();Nodecurr=top.Key;intval=top.Value;// update the valueval=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(newKeyValuePair<Node,int>(curr.right,val));}if(curr.left!=null){st.Push(newKeyValuePair<Node,int>(curr.left,val));}}returnans;}staticvoidMain(string[]args){// Hard coded binary tree.// 6// / \// 3 5// / \ \// 2 5 4 // / \// 7 4Noderoot=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);Console.WriteLine(treePathsSum(root));}}
JavaScript
// JavaScript program to find sum of// all paths from root to leavesclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function which returns the sum of root to leaf path.functiontreePathsSum(root){// base caseif(root===null)return0;// Store pair of node and value// associated with it.letst=[[root,0]];letans=0;while(st.length>0){let[curr,val]=st.pop();// update the valueval=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]);}}returnans;}// Hard coded binary tree.// 6// / \// 3 5// / \ \// 2 5 4 // / \// 7 4letroot=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);console.log(treePathsSum(root));