Given a binary tree, task is to find subtree with maximum sum in tree.
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.
Time Complexity: O(n), where n is number of nodes.
Auxiliary Space: O(n), function call stack size.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find the largest Perfect Subtree in a given Binary Tree
- Find the largest Complete Subtree in a given Binary Tree
- Find largest subtree having identical left and right subtrees
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Even size subtree in n-ary tree
- Subtree with given sum in a Binary Tree
- Queries for DFS of a subtree in a tree
- Subtree of all nodes in a tree using DFS
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Duplicate subtree in Binary Tree | SET 2
- Euler Tour | Subtree Sum using Segment Tree
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.