Open In App

Find largest subtree sum in a tree

Last Updated : 30 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree, the task is to find a subtree with the maximum sum in the tree.

Examples:  

Input:

modify-a-binary-tree-to-get-preorder-traversal-using-right-pointers-only


Output: 28
Explanation: As all the tree elements are positive, the largest subtree sum is equal to sum of all tree elements.

Input:

find-largest-subtree-sum-in-a-tree

Output: 7
Explanation: Subtree with largest sum is:

find-largest-subtree-sum-in-a-tree-2

[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));

Output
7

[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));

Output
7

Next Article
Article Tags :
Practice Tags :

Similar Reads