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