VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-largest-subtree-sum-tree/

⇱ Find largest subtree sum in a tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 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:


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:


Output
7
Comment
Article Tags: