VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-nodes-binary-tree-no-two-adjacent/

⇱ Maximum Sum of Non-Adjacent Nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Sum of Non-Adjacent Nodes

Last Updated : 6 Oct, 2025

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.

Examples:

Input:

πŸ‘ 420046795

Output: 11
Explanation: The maximum sum is sum of node 11.

πŸ‘ 420046796

Input:

πŸ‘ 420046758

Output: 27
Explanation: The maximum sum is sum of nodes 15, and 12, i.e., 27. These nodes are non adjacent.

πŸ‘ 420046759

[Naive Approach] Using Recursion

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).

To avoid this redundancy, we use memorization:

  • We store the result of each node in a hashmap.
  • 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

Comment
Article Tags:
Article Tags: