Find largest subtree sum in a tree
Last Updated :
11 Jul, 2025
Given a Binary Tree, the task is to find a subtree with the maximum sum in the tree.
Examples:
Input:
Output: 28
Explanation: As all the tree elements are positive, the largest subtree sum is equal to sum of all tree elements.
Input:
Output: 7
Explanation: Subtree with largest sum is:
[Expected Approach - 1] Using Recursion - O(n) Time and O(h) Space
The idea is to 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.
Below is the implementation of the above approach:
C++
// C++ program to find largest subtree
// sum in a given binary tree.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Helper function to find largest
// subtree sum recursively.
int findLargestSubtreeSumUtil(Node* root, int& ans) {
// If current node is null then
// return 0 to parent node.
if (root == nullptr)
return 0;
// Subtree sum rooted at current node.
int currSum = root->data +
findLargestSubtreeSumUtil(root->left, ans)
+ findLargestSubtreeSumUtil(root->right, ans);
// Update answer if current subtree
// sum is greater than answer so far.
ans = max(ans, currSum);
// Return current subtree sum to
// its parent node.
return currSum;
}
// Function to find largest subtree sum.
int findLargestSubtreeSum(Node* root) {
// If tree does not exist,
// then answer is 0.
if (root == nullptr)
return 0;
// Variable to store maximum subtree sum.
int ans = INT_MIN;
// Call to recursive function to
// find maximum subtree sum.
findLargestSubtreeSumUtil(root, ans);
return ans;
}
int main() {
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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);
cout << findLargestSubtreeSum(root);
return 0;
}
Java
// Java program to find largest subtree
// sum in a given binary tree.
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
// Helper function to find largest
// subtree sum recursively.
class GfG {
static int findLargestSubtreeSumUtil
(Node root, int[] ans) {
// If current node is null then
// return 0 to parent node.
if (root == null)
return 0;
// Subtree sum rooted at current node.
int currSum = root.data +
findLargestSubtreeSumUtil(root.left, ans)
+ findLargestSubtreeSumUtil(root.right, ans);
// Update answer if current subtree
// sum is greater than answer so far.
ans[0] = Math.max(ans[0], currSum);
// Return current subtree sum to
// its parent node.
return currSum;
}
// Function to find largest subtree sum.
static int findLargestSubtreeSum(Node root) {
// If tree does not exist,
// then answer is 0.
if (root == null)
return 0;
// Variable to store maximum subtree sum.
int[] ans = new int[1];
ans[0] = Integer.MIN_VALUE;
// Call to recursive function to
// find maximum subtree sum.
findLargestSubtreeSumUtil(root, ans);
return ans[0];
}
public static void main(String[] args) {
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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));
}
}
Python
# Python program to find largest subtree
# sum in a given binary tree.
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Helper function to find largest
# subtree sum recursively.
def findLargestSubtreeSumUtil(root, ans):
# If current node is null then
# return 0 to parent node.
if root is None:
return 0
# Subtree sum rooted at current node.
currSum = root.data + findLargestSubtreeSumUtil(root.left, ans) \
+ findLargestSubtreeSumUtil(root.right, ans)
# Update answer if current subtree
# sum is greater than answer so far.
ans[0] = max(ans[0], currSum)
# Return current subtree sum to
# its parent node.
return currSum
# Function to find largest subtree sum.
def findLargestSubtreeSum(root):
# If tree does not exist,
# then answer is 0.
if root is None:
return 0
# Variable to store maximum
# subtree sum.
ans = [float('-inf')]
# Call to recursive function to
# find maximum subtree sum.
findLargestSubtreeSumUtil(root, ans)
return ans[0]
if __name__ == "__main__":
# Representation of the given tree
# 1
# / \
# -2 3
# / \ / \
# 4 5 -6 2
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)
print(findLargestSubtreeSum(root))
C#
// C# program to find largest subtree
// sum in a given binary tree.
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
// Helper function to find largest
// subtree sum recursively.
class GfG {
static int findLargestSubtreeSumUtil
(Node root, ref int ans) {
// If current node is null then
// return 0 to parent node.
if (root == null)
return 0;
// Subtree sum rooted at
// current node.
int currSum = root.data +
findLargestSubtreeSumUtil(root.left, ref ans) +
findLargestSubtreeSumUtil(root.right, ref ans);
// Update answer if current subtree
// sum is greater than answer so far.
ans = Math.Max(ans, currSum);
// Return current subtree sum to
// its parent node.
return currSum;
}
// Function to find largest subtree sum.
static int findLargestSubtreeSum(Node root) {
// If tree does not exist,
// then answer is 0.
if (root == null)
return 0;
// Variable to store maximum subtree sum.
int ans = int.MinValue;
// Call to recursive function to
// find maximum subtree sum.
findLargestSubtreeSumUtil(root, ref ans);
return ans;
}
static void Main(string[] args) {
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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));
}
}
JavaScript
// JavaScript program to find largest subtree
// sum in a given binary tree.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Helper function to find largest
// subtree sum recursively.
function findLargestSubtreeSumUtil(root, ans) {
// If current node is null then
// return 0 to parent node.
if (root === null)
return 0;
// Subtree sum rooted at current node.
let currSum = root.data +
findLargestSubtreeSumUtil(root.left, ans) +
findLargestSubtreeSumUtil(root.right, ans);
// Update answer if current subtree
// sum is greater than answer so far.
ans[0] = Math.max(ans[0], currSum);
// Return current subtree sum to
// its parent node.
return currSum;
}
// Function to find largest subtree sum.
function findLargestSubtreeSum(root) {
// If tree does not exist,
// then answer is 0.
if (root === null)
return 0;
// Variable to store maximum
// subtree sum.
let ans = [-Infinity];
// Call to recursive function to
// find maximum subtree sum.
findLargestSubtreeSumUtil(root, ans);
return ans[0];
}
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
let 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));
[Expected Approach - 2] Using BFS - O(n) Time and O(n) Space
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)
Below is the implementation of the above approach:
C++
// C++ program to find largest subtree
// sum in a given binary tree using BFS
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
int findLargestSubtreeSum(Node* root) {
// Base case when tree is empty
if (root == nullptr)
return 0;
int ans = INT_MIN;
queue<Node*> q;
// Vector of Vector for storing
// nodes at a particular level
vector<vector<Node*> > levels;
// Map for storing sum of subtree
// rooted at a particular node
unordered_map<Node*, int> subtreeSum;
// Push root to the queue
q.push(root);
while (!q.empty()) {
int n = q.size();
vector<Node*> level;
while (n--) {
Node* node = q.front();
// Push current node to current
// level vector
level.push_back(node);
// Add left & right child of node
// in the queue
if (node->left)
q.push(node->left);
if (node->right)
q.push(node->right);
q.pop();
}
// add current level to levels
// vector
levels.push_back(level);
}
// Traverse all levels from bottom
//most level to top most level
for (int i = levels.size() - 1; i >= 0; i--) {
for (auto e : levels[i]) {
// add value of current node
subtreeSum[e] = e->data;
// If node has left child, add the subtree sum
// of subtree rooted at left child
if (e->left)
subtreeSum[e] += subtreeSum[e->left];
// If node has right child, add the subtree sum
// of subtree rooted at right child
if (e->right)
subtreeSum[e] += subtreeSum[e->right];
// update ans to maximum of ans and sum of
// subtree rooted at current node
ans = max(ans, subtreeSum[e]);
}
}
return ans;
}
int main() {
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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);
cout << findLargestSubtreeSum(root) << endl;
return 0;
}
Java
// Java program to find largest subtree
// sum in a given binary tree using BFS
import java.util.*;
class Node {
int data;
Node left;
Node right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
static int findLargestSubtreeSum(Node root) {
// Base case when tree is empty
if (root == null)
return 0;
int ans = Integer.MIN_VALUE;
// Queue for level order traversal
Queue<Node> q = new LinkedList<>();
// List of List for storing
// nodes at a particular level
List<List<Node>> levels = new ArrayList<>();
// Map for storing sum of subtree
// rooted at a particular node
HashMap<Node, Integer> subtreeSum =
new HashMap<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
List<Node> level = new ArrayList<>();
while (n-- > 0) {
Node node = q.poll();
// Push current node to current
// level list
level.add(node);
// Add left & right child of node
// in the queue
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
// add current level to
// levels list
levels.add(level);
}
// Traverse all levels from bottom
// most level to top most level
for (int i = levels.size() - 1; i >= 0; i--) {
for (Node e : levels.get(i)) {
// add value of current node
subtreeSum.put(e, e.data);
// If node has left child, add the subtree sum
// of subtree rooted at left child
if (e.left != null)
subtreeSum.put(e, subtreeSum.get(e)
+ subtreeSum.get(e.left));
// If node has right child, add the subtree sum
// of subtree rooted at right child
if (e.right != null)
subtreeSum.put(e, subtreeSum.get(e)
+ subtreeSum.get(e.right));
// update ans to maximum of ans and sum of
// subtree rooted at current node
ans = Math.max(ans, subtreeSum.get(e));
}
}
return ans;
}
public static void main(String[] args) {
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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));
}
}
Python
# Python program to find largest subtree
# sum in a given binary tree using BFS
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
def findLargestSubtreeSum(root):
# Base case when tree is empty
if root is None:
return 0
ans = float('-inf')
# Queue for level order
# traversal
q = []
# List of List for storing
# nodes at a particular level
levels = []
# Dictionary for storing sum of subtree
# rooted at a particular node
subtreeSum = {}
# Push root to the queue
q.append(root)
while q:
n = len(q)
level = []
while n > 0:
node = q.pop(0)
# Push current node to current
# level list
level.append(node)
# Add left & right child of node
# in the queue
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
n -= 1
# add current level to
# levels list
levels.append(level)
# Traverse all levels from bottom most level to top
# most level
for i in range(len(levels) - 1, -1, -1):
for e in levels[i]:
# add value of current node
subtreeSum[e] = e.data
# If node has left child, add the subtree sum
# of subtree rooted at left child
if e.left:
subtreeSum[e] += subtreeSum[e.left]
# If node has right child, add the subtree sum
# of subtree rooted at right child
if e.right:
subtreeSum[e] += subtreeSum[e.right]
# update ans to maximum of ans and sum of
# subtree rooted at current node
ans = max(ans, subtreeSum[e])
return ans
if __name__ == "__main__":
# Representation of the given tree
# 1
# / \
# -2 3
# / \ / \
# 4 5 -6 2
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)
print(findLargestSubtreeSum(root))
C#
// C# program to find largest subtree
// sum in a given binary tree using BFS
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left;
public Node right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
static int findLargestSubtreeSum(Node root) {
// Base case when tree is empty
if (root == null)
return 0;
int ans = int.MinValue;
// Queue for level order traversal
Queue<Node> q = new Queue<Node>();
// List of List for storing
// nodes at a particular level
List<List<Node>> levels =
new List<List<Node>>();
// Dictionary for storing sum of subtree
// rooted at a particular node
Dictionary<Node, int> subtreeSum =
new Dictionary<Node, int>();
// Push root to the queue
q.Enqueue(root);
while (q.Count > 0) {
int n = q.Count;
List<Node> level = new List<Node>();
while (n-- > 0) {
Node node = q.Dequeue();
// Push current node to current
// level list
level.Add(node);
// Add left & right child of node
// in the queue
if (node.left != null)
q.Enqueue(node.left);
if (node.right != null)
q.Enqueue(node.right);
}
// add current level to
// levels list
levels.Add(level);
}
// Traverse all levels from bottom
// most level to top most level
for (int i = levels.Count - 1; i >= 0; i--) {
foreach (var e in levels[i]) {
// add value of current node
subtreeSum[e] = e.data;
// If node has left child, add the subtree sum
// of subtree rooted at left child
if (e.left != null)
subtreeSum[e] += subtreeSum[e.left];
// If node has right child, add the subtree sum
// of subtree rooted at right child
if (e.right != null)
subtreeSum[e] += subtreeSum[e.right];
// update ans to maximum of ans and sum of
// subtree rooted at current node
ans = Math.Max(ans, subtreeSum[e]);
}
}
return ans;
}
static void Main() {
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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));
}
}
JavaScript
// JavaScript program to find largest subtree
// sum in a given binary tree using BFS
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
function findLargestSubtreeSum(root) {
// Base case when tree is empty
if (root === null)
return 0;
let ans = Number.NEGATIVE_INFINITY;
// Queue for level order traversal
const q = [];
// Array of Array for storing
// nodes at a particular level
const levels = [];
// Map for storing sum of subtree
// rooted at a particular node
const subtreeSum = new Map();
// Push root to the queue
q.push(root);
while (q.length > 0) {
const n = q.length;
const level = [];
for (let i = 0; i < n; i++) {
const node = q.shift();
// Push current node to current
// level array
level.push(node);
// Add left & right child of node
// in the queue
if (node.left)
q.push(node.left);
if (node.right)
q.push(node.right);
}
// add current level to levels array
levels.push(level);
}
// Traverse all levels from bottom most level to top
// most level
for (let i = levels.length - 1; i >= 0; i--) {
for (const e of levels[i]) {
// add value of current node
subtreeSum.set(e, e.data);
// If node has left child, add the subtree sum
// of subtree rooted at left child
if (e.left)
subtreeSum.set(e, subtreeSum.get(e)
+ subtreeSum.get(e.left));
// If node has right child, add the subtree sum
// of subtree rooted at right child
if (e.right)
subtreeSum.set(e, subtreeSum.get(e)
+ subtreeSum.get(e.right));
// update ans to maximum of ans and sum of
// subtree rooted at current node
ans = Math.max(ans, subtreeSum.get(e));
}
}
return ans;
}
// Representation of the given tree
// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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));
Find largest subtree sum in a tree
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