Given the root of a binary tree with integer values, Find the maximum sum of node values such that no two nodes connected by an edge are both included in the sum.
We can solve this problem by considering the fact that both node and its immediate children canβt be in sum at the same time.
Include the current node's value in the sum: In this case, we cannot include the values of its immediate children in the sum. Therefore, we recursively call the function on the grandchildren of the current node.
Exclude the current node's value in the sum: In this case, we are allowed to include the values of its immediate children in the sum. So, we recursively call the function on the immediate children of the current node.
Finally we will choose maximum from both of the results.
Output
11
Time Complexity: O(2n), Auxiliary Space: O(h), where h is height of binary tree due to recursion stack space
[Expected Approach 1] Using Top-Down DP (Memorization) - O(n) Time and O(n) Space
The naive approach leads to recalculating results for the same nodes multiple times. For example, if we include the root node, we recursively compute the sum for its grandchildren (nodes 4 and 5). But if we exclude the root, we compute the sum for its children, and node 3 also computes the sum for its children (4 and 5 again).
When a node's value is needed again, we directly return it from the map instead of recalculating.
Output
11
[Expected Approach 2] Using Include-Exclude Strategy
In this approach, we return a list for each node in the binary tree such that the first of the pair indicates the maximum sum when the data of a node is included and the second indicates the maximum sum when the data of a particular node is not included.
Output
11
Time Complexity: O(n) Auxiliary Space: O(h), where h is height of binary tree due to recursion stack space