Find largest subtree sum in a tree
Last Updated :
18 Apr, 2023
Given a binary tree, task is to find subtree with maximum sum in tree.
Examples:
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
Output : 28
As all the tree elements are positive,
the largest subtree sum is equal to
sum of all tree elements.
Input : 1
/ \
-2 3
/ \ / \
4 5 -6 2
Output : 7
Subtree with largest sum is :
-2
/ \
4 5
Also, entire tree sum is also 7.
Approach : Do post order traversal of the binary tree. At every node, find left subtree value and right subtree value recursively. The value of subtree rooted at current node is equal to sum of current node value, left node subtree sum and right node subtree sum. Compare current subtree sum with overall maximum subtree sum so far.
Implementation :
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
int findLargestSubtreeSumUtil(Node* root, int & ans)
{
if (root == NULL)
return 0;
int currSum = root->key +
findLargestSubtreeSumUtil(root->left, ans)
+ findLargestSubtreeSumUtil(root->right, ans);
ans = max(ans, currSum);
return currSum;
}
int findLargestSubtreeSum(Node* root)
{
if (root == NULL)
return 0;
int ans = INT_MIN;
findLargestSubtreeSumUtil(root, ans);
return ans;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(-2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(-6);
root->right->right = newNode(2);
cout << findLargestSubtreeSum(root);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int key;
Node left, right;
}
static class INT
{
int v;
INT( int a)
{
v = a;
}
}
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null ;
return temp;
}
static int findLargestSubtreeSumUtil(Node root,
INT ans)
{
if (root == null )
return 0 ;
int currSum = root.key +
findLargestSubtreeSumUtil(root.left, ans) +
findLargestSubtreeSumUtil(root.right, ans);
ans.v = Math.max(ans.v, currSum);
return currSum;
}
static int findLargestSubtreeSum(Node root)
{
if (root == null )
return 0 ;
INT ans = new INT(- 9999999 );
findLargestSubtreeSumUtil(root, ans);
return ans.v;
}
public static void main(String args[])
{
Node root = newNode( 1 );
root.left = newNode(- 2 );
root.right = newNode( 3 );
root.left.left = newNode( 4 );
root.left.right = newNode( 5 );
root.right.left = newNode(- 6 );
root.right.right = newNode( 2 );
System.out.println(findLargestSubtreeSum(root));
}
}
|
Python3
class newNode:
def __init__( self , key):
self .key = key
self .left = self .right = None
def findLargestSubtreeSumUtil(root, ans):
if (root = = None ):
return 0
currSum = (root.key +
findLargestSubtreeSumUtil(root.left, ans) +
findLargestSubtreeSumUtil(root.right, ans))
ans[ 0 ] = max (ans[ 0 ], currSum)
return currSum
def findLargestSubtreeSum(root):
if (root = = None ):
return 0
ans = [ - 999999999999 ]
findLargestSubtreeSumUtil(root, ans)
return ans[ 0 ]
if __name__ = = '__main__' :
root = newNode( 1 )
root.left = newNode( - 2 )
root.right = newNode( 3 )
root.left.left = newNode( 4 )
root.left.right = newNode( 5 )
root.right.left = newNode( - 6 )
root.right.right = newNode( 2 )
print (findLargestSubtreeSum(root))
|
C#
using System;
public class GFG
{
public class Node
{
public int key;
public Node left, right;
}
public class INT
{
public int v;
public INT( int a)
{
v = a;
}
}
public static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null ;
return temp;
}
public static int findLargestSubtreeSumUtil(Node root, INT ans)
{
if (root == null )
{
return 0;
}
int currSum = root.key + findLargestSubtreeSumUtil(root.left, ans)
+ findLargestSubtreeSumUtil(root.right, ans);
ans.v = Math.Max(ans.v, currSum);
return currSum;
}
public static int findLargestSubtreeSum(Node root)
{
if (root == null )
{
return 0;
}
INT ans = new INT(-9999999);
findLargestSubtreeSumUtil(root, ans);
return ans.v;
}
public static void Main( string [] args)
{
Node root = newNode(1);
root.left = newNode(-2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(-6);
root.right.right = newNode(2);
Console.WriteLine(findLargestSubtreeSum(root));
}
}
|
Javascript
<script>
class Node
{
constructor(key) {
this .left = null ;
this .right = null ;
this .key = key;
}
}
let v;
function newNode(key)
{
let temp = new Node(key);
return temp;
}
function findLargestSubtreeSumUtil(root)
{
if (root == null )
return 0;
let currSum = root.key +
findLargestSubtreeSumUtil(root.left) +
findLargestSubtreeSumUtil(root.right);
v = Math.max(v, currSum);
return currSum;
}
function findLargestSubtreeSum(root)
{
if (root == null )
return 0;
v = -9999999;
findLargestSubtreeSumUtil(root);
return v;
}
let root = newNode(1);
root.left = newNode(-2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(-6);
root.right.right = newNode(2);
document.write(findLargestSubtreeSum(root));
</script>
|
Complexity Analysis:
- Time Complexity: O(n), where n is the number of nodes.
- Auxiliary Space: O(n), function call stack size.
Using DFS approach:
The idea is to use depth first search recursively call for every subtree in left and right including root node and calculate for maximum sum for the same subtree.
Steps to solve the problem:
- initialize ans variable with int min.
- first check for the base condition.
- calculate all the subtree with maximum sum in the left.
- calculate all the subtree with maximum sum in the right.
- store temporarily maximum value of left and right
- update that temporarily stored value with maximum of sum of left , right and root node and that temp value.
- update the ans variable to max(ans,tempmax).
- return the sum.
Implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
int ans = INT_MIN;
int dfs(Node* root)
{
if (root == NULL)
return 0;
if (root->left == NULL and root->right == NULL)
return root->key;
int sumleft = dfs(root->left);
int sumright = dfs(root->right);
int sumrootnode = sumleft + sumright + root->key;
int tempmax = max(sumleft, sumright);
tempmax = max(tempmax, sumrootnode);
ans = max(ans, tempmax);
return sumrootnode;
}
int findLargestSubtreeSum(Node* root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return root->key;
int x = dfs(root);
return ans;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(-2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(-6);
root->right->right = newNode(2);
cout << findLargestSubtreeSum(root);
return 0;
}
|
Java
import java.io.*;
class GFG {
static class Node {
public int key;
public Node left, right;
}
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return temp;
}
static int ans = Integer.MIN_VALUE;
static int dfs(Node root)
{
if (root == null )
return 0 ;
if (root.left == null && root.right == null )
return root.key;
int sumleft = dfs(root.left);
int sumright = dfs(root.right);
int sumrootnode = sumleft + sumright + root.key;
int tempmax = Math.max(sumleft, sumright);
tempmax = Math.max(tempmax, sumrootnode);
ans = Math.max(ans, tempmax);
return sumrootnode;
}
static int findLargestSubtreeSum(Node root)
{
if (root == null )
return 0 ;
if (root.left == null && root.right == null )
return root.key;
int x = dfs(root);
return ans;
}
public static void main(String[] args)
{
Node root = newNode( 1 );
root.left = newNode(- 2 );
root.right = newNode( 3 );
root.left.left = newNode( 4 );
root.left.right = newNode( 5 );
root.right.left = newNode(- 6 );
root.right.right = newNode( 2 );
System.out.println(findLargestSubtreeSum(root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
ans = float ( "-infinity" )
def findLargestSubtreeSum(root):
if root is None :
return 0
if root.left is None and root.right is None :
return root.data
sumleft = findLargestSubtreeSum(root.left)
sumright = findLargestSubtreeSum(root.right)
sumrootnode = sumleft + sumright + root.data
tempmax = max (sumleft, sumright)
tempmax = max (tempmax, sumrootnode)
global ans
ans = max (ans, tempmax)
return sumrootnode
if __name__ = = '__main__' :
root = Node( 1 )
root.left = Node( - 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.right.left = Node( - 6 )
root.right.right = Node( 2 )
findLargestSubtreeSum(root)
print (ans)
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
class Node {
public int key;
public Node left, right;
};
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return temp;
}
static int ans = Int32.MinValue;
static int dfs(Node root)
{
if (root == null )
return 0;
if (root.left == null && root.right == null )
return root.key;
int sumleft = dfs(root.left);
int sumright = dfs(root.right);
int sumrootnode = sumleft + sumright + root.key;
int tempmax = Math.Max(sumleft, sumright);
tempmax = Math.Max(tempmax, sumrootnode);
ans = Math.Max(ans, tempmax);
return sumrootnode;
}
static int findLargestSubtreeSum(Node root)
{
if (root == null )
return 0;
if (root.left == null && root.right == null )
return root.key;
int x = dfs(root);
return ans;
}
public static void Main()
{
Node root = newNode(1);
root.left = newNode(-2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(-6);
root.right.right = newNode(2);
Console.Write(findLargestSubtreeSum(root));
}
}
|
Javascript
class Node{
constructor(key){
this .key = key;
this .left = null ;
this .right = null ;
}
}
function newNode(key){
let temp = new Node();
temp.key = key;
temp.left = temp.right = null ;
return temp;
}
let ans = Number.MIN_VALUE;
function dfs(root){
if (root == null ) return 0;
if (root.left == null && root.right == null ) return root.key;
let sumleft = dfs(root.left);
let sumright = dfs(root.right);
let sumrootnode = sumleft + sumright + root.key;
let tempmax = Math.max(sumleft, sumright);
tempmax = Math.max(tempmax, sumrootnode);
ans = Math.max(ans, tempmax);
return sumrootnode;
}
function findLargestSubtreeSum(root){
if (root == null )
return 0;
if (root.left == null && root.right == null )
return root.key;
let x = dfs(root);
return ans;
}
let root = newNode(1);
root.left = newNode(-2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(-6);
root.right.right = newNode(2);
document.write(findLargestSubtreeSum(root));
|
Time Complexity: O(n)
Auxiliary Space: O(h) where h is the height of the tree
this approach is contributed by Prateek Kumar Singh (pkrsingh025).
Using BFS approach :
The idea is to use breadth first search to store nodes (level wise) at each level in some container and then traverse these levels in reverse order from bottom level to top level and keep storing the subtree sum value rooted at nodes at each level. We can then reuse these values for upper levels.
subtree sum rooted at node = value of node + (subtree sum rooted at node->left) + (subtree sum rooted at node->right)
Steps to solve the problem:
- First, check if tree is empty, then return 0.
- Initialize ans variable with INT_MIN.
- Create list of list of Nodes to store nodes at each level.
- Also, create an map to store the sum of values for the subtree rooted at a particular node.
- Now perform BFS by creating a queue and pushing the root in the queue.
- Create a temporary list for storing nodes at current level
- After traversing all nodes at current level, push this temporary list into our list of list of nodes.
- Now, start traversing our levels list in reverse manner starting from last level towards the 1st level
- For each level, traverse the nodes and find the subtree sum rooted at this node. We will use the already stored subtree sum values for nodes at below level
- For each node traversed, Update the ans variable to maximum of ans and the value of subtree sum rooted at current node.
- Return the ans.
Implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
int findLargestSubtreeSum(Node* root)
{
if (root == NULL)
return 0;
int ans = INT_MIN;
queue<Node*> q;
vector<vector<Node*> > levels;
unordered_map<Node*, int > subtreeSum;
q.push(root);
while (!q.empty()) {
int n = q.size();
vector<Node*> level;
while (n--) {
Node* node = q.front();
level.push_back(node);
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
q.pop();
}
levels.push_back(level);
}
for ( int i = levels.size() - 1; i >= 0; i--) {
for ( auto e : levels[i]) {
subtreeSum[e] = e->key;
if (e->left)
subtreeSum[e] += subtreeSum[e->left];
if (e->right)
subtreeSum[e] += subtreeSum[e->right];
ans = max(ans, subtreeSum[e]);
}
}
return ans;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(-2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(-6);
root->right->right = newNode(2);
cout << findLargestSubtreeSum(root);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
class Node {
int key;
Node left, right;
Node( int key)
{
this .key = key;
left = right = null ;
}
}
public class Main {
static int findLargestSubtreeSum(Node root)
{
if (root == null )
return 0 ;
int ans = Integer.MIN_VALUE;
Queue<Node> q = new LinkedList<>();
Vector<Vector<Node> > levels = new Vector<>();
HashMap<Node, Integer> subtreeSum = new HashMap<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
Vector<Node> level = new Vector<>();
while (n-- > 0 ) {
Node node = q.poll();
level.add(node);
if (node.left != null )
q.add(node.left);
if (node.right != null )
q.add(node.right);
}
levels.add(level);
}
for ( int i = levels.size() - 1 ; i >= 0 ; i--) {
for (Node e : levels.get(i)) {
subtreeSum.put(e, e.key);
if (e.left != null )
subtreeSum.put(
e, subtreeSum.get(e)
+ subtreeSum.get(e.left));
if (e.right != null )
subtreeSum.put(
e, subtreeSum.get(e)
+ subtreeSum.get(e.right));
ans = Math.max(ans, subtreeSum.get(e));
}
}
return ans;
}
public static void main(String[] args)
{
Node root = new Node( 1 );
root.left = new Node(- 2 );
root.right = new Node( 3 );
root.left.left = new Node( 4 );
root.left.right = new Node( 5 );
root.right.left = new Node(- 6 );
root.right.right = new Node( 2 );
System.out.println(findLargestSubtreeSum(root));
}
}
|
Javascript
class Node {
constructor(key) {
this .key = key;
this .left = null ;
this .right = null ;
}
}
function findLargestSubtreeSum(root) {
if (root === null ) return 0;
let ans = -Infinity;
const q = [];
const levels = [];
const subtreeSum = new Map();
q.push(root);
while (q.length > 0) {
let n = q.length;
let level = [];
while (n-- > 0) {
const node = q.shift();
level.push(node);
if (node.left !== null ) q.push(node.left);
if (node.right !== null ) q.push(node.right);
}
levels.push(level);
}
for (let i = levels.length - 1; i >= 0; i--) {
const level = levels[i];
for (let j = 0; j < level.length; j++) {
const e = level[j];
subtreeSum.set(e, e.key);
if (e.left !== null ) {
subtreeSum.set(
e,
subtreeSum.get(e) + subtreeSum.get(e.left)
);
}
if (e.right !== null ) {
subtreeSum.set(
e,
subtreeSum.get(e) + subtreeSum.get(e.right)
);
}
ans = Math.max(ans, subtreeSum.get(e));
}
}
return ans;
}
const root = new Node(1);
root.left = new Node(-2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(-6);
root.right.right = new Node(2);
console.log(findLargestSubtreeSum(root));
|
C#
using System;
using System.Collections.Generic;
class Node {
public int key;
public Node left, right;
public Node( int key)
{
this .key = key;
left = right = null ;
}
}
public class GFG {
static int findLargestSubtreeSum(Node root)
{
if (root == null )
return 0;
int ans = int .MinValue;
Queue<Node> q = new Queue<Node>();
List<List<Node> > levels = new List<List<Node> >();
Dictionary<Node, int > subtreeSum
= new Dictionary<Node, int >();
q.Enqueue(root);
while (q.Count != 0) {
int n = q.Count;
List<Node> level = new List<Node>();
while (n-- > 0) {
Node node = q.Dequeue();
level.Add(node);
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
}
levels.Add(level);
}
for ( int i = levels.Count - 1; i >= 0; i--) {
foreach (Node e in levels[i])
{
subtreeSum[e] = e.key;
if (e.left != null )
subtreeSum[e] += subtreeSum[e.left];
if (e.right != null )
subtreeSum[e] += subtreeSum[e.right];
ans = Math.Max(ans, subtreeSum[e]);
}
}
return ans;
}
static public void Main()
{
Node root = new Node(1);
root.left = new Node(-2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(-6);
root.right.right = new Node(2);
Console.WriteLine(findLargestSubtreeSum(root));
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def newNode(key):
temp = Node(key)
return temp
def findLargestSubtreeSum(root):
if root is None :
return 0
ans = float ( '-inf' )
q = deque()
levels = []
subtreeSum = {}
q.append(root)
while len (q) > 0 :
n = len (q)
level = []
while n > 0 :
node = q.popleft()
level.append(node)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
n - = 1
levels.append(level)
for i in range ( len (levels) - 1 , - 1 , - 1 ):
for e in levels[i]:
subtreeSum[e] = e.key
if e.left:
subtreeSum[e] + = subtreeSum[e.left]
if e.right:
subtreeSum[e] + = subtreeSum[e.right]
ans = max (ans, subtreeSum[e])
return ans
if __name__ = = '__main__' :
root = newNode( 1 )
root.left = newNode( - 2 )
root.right = newNode( 3 )
root.left.left = newNode( 4 )
root.left.right = newNode( 5 )
root.right.left = newNode( - 6 )
root.right.right = newNode( 2 )
print (findLargestSubtreeSum(root))
|
Time Complexity = Time complexity of BFS = O(N) where N is the number of nodes in the tree
Space Complexity = Space to store Nodes + Space to store sum values at each Node = O(N) + O(N) = O(N)
This approach is contributed by Piyush Garg (infinity4321cg)
Please Login to comment...