[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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Helper function to find largest// subtree sum recursively.intfindLargestSubtreeSumUtil(Node*root,int&ans){// If current node is null then// return 0 to parent node.if(root==nullptr)return0;// Subtree sum rooted at current node.intcurrSum=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.returncurrSum;}// Function to find largest subtree sum.intfindLargestSubtreeSum(Node*root){// If tree does not exist, // then answer is 0.if(root==nullptr)return0;// Variable to store maximum subtree sum.intans=INT_MIN;// Call to recursive function to// find maximum subtree sum.findLargestSubtreeSumUtil(root,ans);returnans;}intmain(){// Representation of the given tree// 1// / \ // -2 3// / \ / \ // 4 5 -6 2Node*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);return0;}
Java
// Java program to find largest subtree// sum in a given binary tree.classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}// Helper function to find largest// subtree sum recursively.classGfG{staticintfindLargestSubtreeSumUtil(Noderoot,int[]ans){// If current node is null then// return 0 to parent node.if(root==null)return0;// Subtree sum rooted at current node.intcurrSum=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.returncurrSum;}// Function to find largest subtree sum.staticintfindLargestSubtreeSum(Noderoot){// If tree does not exist, // then answer is 0.if(root==null)return0;// Variable to store maximum subtree sum.int[]ans=newint[1];ans[0]=Integer.MIN_VALUE;// Call to recursive function to// find maximum subtree sum.findLargestSubtreeSumUtil(root,ans);returnans[0];}publicstaticvoidmain(String[]args){// Representation of the given tree// 1// / \// -2 3// / \ / \// 4 5 -6 2Noderoot=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));}}
Python
# Python program to find largest subtree# sum in a given binary tree.classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Helper function to find largest# subtree sum recursively.deffindLargestSubtreeSumUtil(root,ans):# If current node is null then# return 0 to parent node.ifrootisNone:return0# 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.returncurrSum# Function to find largest subtree sum.deffindLargestSubtreeSum(root):# If tree does not exist, # then answer is 0.ifrootisNone:return0# Variable to store maximum# subtree sum.ans=[float('-inf')]# Call to recursive function to# find maximum subtree sum.findLargestSubtreeSumUtil(root,ans)returnans[0]if__name__=="__main__":# Representation of the given tree# 1# / \# -2 3# / \ / \# 4 5 -6 2root=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.usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}// Helper function to find largest// subtree sum recursively.classGfG{staticintfindLargestSubtreeSumUtil(Noderoot,refintans){// If current node is null then// return 0 to parent node.if(root==null)return0;// Subtree sum rooted at// current node.intcurrSum=root.data+findLargestSubtreeSumUtil(root.left,refans)+findLargestSubtreeSumUtil(root.right,refans);// 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.returncurrSum;}// Function to find largest subtree sum.staticintfindLargestSubtreeSum(Noderoot){// If tree does not exist,// then answer is 0.if(root==null)return0;// Variable to store maximum subtree sum.intans=int.MinValue;// Call to recursive function to// find maximum subtree sum.findLargestSubtreeSumUtil(root,refans);returnans;}staticvoidMain(string[]args){// Representation of the given tree// 1// / \// -2 3// / \ / \// 4 5 -6 2Noderoot=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
// JavaScript program to find largest subtree// sum in a given binary tree.classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Helper function to find largest// subtree sum recursively.functionfindLargestSubtreeSumUtil(root,ans){// If current node is null then// return 0 to parent node.if(root===null)return0;// Subtree sum rooted at current node.letcurrSum=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.returncurrSum;}// Function to find largest subtree sum.functionfindLargestSubtreeSum(root){// If tree does not exist, // then answer is 0.if(root===null)return0;// Variable to store maximum // subtree sum.letans=[-Infinity];// Call to recursive function to// find maximum subtree sum.findLargestSubtreeSumUtil(root,ans);returnans[0];}// Representation of the given tree// 1// / \// -2 3// / \ / \// 4 5 -6 2letroot=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.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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};intfindLargestSubtreeSum(Node*root){// Base case when tree is emptyif(root==nullptr)return0;intans=INT_MIN;queue<Node*>q;// Vector of Vector for storing// nodes at a particular levelvector<vector<Node*>>levels;// Map for storing sum of subtree // rooted at a particular nodeunordered_map<Node*,int>subtreeSum;// Push root to the queueq.push(root);while(!q.empty()){intn=q.size();vector<Node*>level;while(n--){Node*node=q.front();// Push current node to current// level vectorlevel.push_back(node);// Add left & right child of node// in the queueif(node->left)q.push(node->left);if(node->right)q.push(node->right);q.pop();}// add current level to levels// vectorlevels.push_back(level);}// Traverse all levels from bottom//most level to top most levelfor(inti=levels.size()-1;i>=0;i--){for(autoe:levels[i]){// add value of current nodesubtreeSum[e]=e->data;// If node has left child, add the subtree sum// of subtree rooted at left childif(e->left)subtreeSum[e]+=subtreeSum[e->left];// If node has right child, add the subtree sum// of subtree rooted at right childif(e->right)subtreeSum[e]+=subtreeSum[e->right];// update ans to maximum of ans and sum of// subtree rooted at current nodeans=max(ans,subtreeSum[e]);}}returnans;}intmain(){// Representation of the given tree// 1// / \ // -2 3// / \ / \ // 4 5 -6 2Node*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)<<endl;return0;}
Java
// Java program to find largest subtree// sum in a given binary tree using BFSimportjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}classGfG{staticintfindLargestSubtreeSum(Noderoot){// Base case when tree is emptyif(root==null)return0;intans=Integer.MIN_VALUE;// Queue for level order traversalQueue<Node>q=newLinkedList<>();// List of List for storing// nodes at a particular levelList<List<Node>>levels=newArrayList<>();// Map for storing sum of subtree // rooted at a particular nodeHashMap<Node,Integer>subtreeSum=newHashMap<>();q.add(root);while(!q.isEmpty()){intn=q.size();List<Node>level=newArrayList<>();while(n-->0){Nodenode=q.poll();// Push current node to current // level listlevel.add(node);// Add left & right child of node// in the queueif(node.left!=null)q.add(node.left);if(node.right!=null)q.add(node.right);}// add current level to// levels listlevels.add(level);}// Traverse all levels from bottom // most level to top most levelfor(inti=levels.size()-1;i>=0;i--){for(Nodee:levels.get(i)){// add value of current nodesubtreeSum.put(e,e.data);// If node has left child, add the subtree sum// of subtree rooted at left childif(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 childif(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 nodeans=Math.max(ans,subtreeSum.get(e));}}returnans;}publicstaticvoidmain(String[]args){// Representation of the given tree// 1// / \// -2 3// / \ / \// 4 5 -6 2Noderoot=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));}}
Python
# Python program to find largest subtree# sum in a given binary tree using BFSclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedeffindLargestSubtreeSum(root):# Base case when tree is emptyifrootisNone:return0ans=float('-inf')# Queue for level order# traversalq=[]# List of List for storing# nodes at a particular levellevels=[]# Dictionary for storing sum of subtree # rooted at a particular nodesubtreeSum={}# Push root to the queueq.append(root)whileq:n=len(q)level=[]whilen>0:node=q.pop(0)# Push current node to current# level listlevel.append(node)# Add left & right child of node# in the queueifnode.left:q.append(node.left)ifnode.right:q.append(node.right)n-=1# add current level to # levels listlevels.append(level)# Traverse all levels from bottom most level to top# most levelforiinrange(len(levels)-1,-1,-1):foreinlevels[i]:# add value of current nodesubtreeSum[e]=e.data# If node has left child, add the subtree sum# of subtree rooted at left childife.left:subtreeSum[e]+=subtreeSum[e.left]# If node has right child, add the subtree sum# of subtree rooted at right childife.right:subtreeSum[e]+=subtreeSum[e.right]# update ans to maximum of ans and sum of# subtree rooted at current nodeans=max(ans,subtreeSum[e])returnansif__name__=="__main__":# Representation of the given tree# 1# / \# -2 3# / \ / \# 4 5 -6 2root=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 BFSusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGfG{staticintfindLargestSubtreeSum(Noderoot){// Base case when tree is emptyif(root==null)return0;intans=int.MinValue;// Queue for level order traversalQueue<Node>q=newQueue<Node>();// List of List for storing// nodes at a particular levelList<List<Node>>levels=newList<List<Node>>();// Dictionary for storing sum of subtree // rooted at a particular nodeDictionary<Node,int>subtreeSum=newDictionary<Node,int>();// Push root to the queueq.Enqueue(root);while(q.Count>0){intn=q.Count;List<Node>level=newList<Node>();while(n-->0){Nodenode=q.Dequeue();// Push current node to current// level listlevel.Add(node);// Add left & right child of node// in the queueif(node.left!=null)q.Enqueue(node.left);if(node.right!=null)q.Enqueue(node.right);}// add current level to // levels listlevels.Add(level);}// Traverse all levels from bottom // most level to top most levelfor(inti=levels.Count-1;i>=0;i--){foreach(vareinlevels[i]){// add value of current nodesubtreeSum[e]=e.data;// If node has left child, add the subtree sum// of subtree rooted at left childif(e.left!=null)subtreeSum[e]+=subtreeSum[e.left];// If node has right child, add the subtree sum// of subtree rooted at right childif(e.right!=null)subtreeSum[e]+=subtreeSum[e.right];// update ans to maximum of ans and sum of// subtree rooted at current nodeans=Math.Max(ans,subtreeSum[e]);}}returnans;}staticvoidMain(){// Representation of the given tree// 1// / \// -2 3// / \ / \// 4 5 -6 2Noderoot=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
// JavaScript program to find largest subtree// sum in a given binary tree using BFSclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionfindLargestSubtreeSum(root){// Base case when tree is emptyif(root===null)return0;letans=Number.NEGATIVE_INFINITY;// Queue for level order traversalconstq=[];// Array of Array for storing// nodes at a particular levelconstlevels=[];// Map for storing sum of subtree // rooted at a particular nodeconstsubtreeSum=newMap();// Push root to the queueq.push(root);while(q.length>0){constn=q.length;constlevel=[];for(leti=0;i<n;i++){constnode=q.shift();// Push current node to current // level arraylevel.push(node);// Add left & right child of node// in the queueif(node.left)q.push(node.left);if(node.right)q.push(node.right);}// add current level to levels arraylevels.push(level);}// Traverse all levels from bottom most level to top// most levelfor(leti=levels.length-1;i>=0;i--){for(consteoflevels[i]){// add value of current nodesubtreeSum.set(e,e.data);// If node has left child, add the subtree sum// of subtree rooted at left childif(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 childif(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 nodeans=Math.max(ans,subtreeSum.get(e));}}returnans;}// Representation of the given tree// 1// / \// -2 3// / \ / \// 4 5 -6 2constroot=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.log(findLargestSubtreeSum(root));