The Wayback Machine - https://web.archive.org/web/20250306101446/https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/
Open In App

Maximum sum of nodes in Binary tree such that no two are adjacent

Last Updated : 25 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we can’t take any of its children in consideration and vice versa.

Examples:  

Input:

Maximum-sum-of-nodes-in-Binary-tree-such-that-no-two-are-adjacent-1

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

Maximum-sum-of-nodes-in-Binary-tree-such-that-no-two-are-adjacent--2


Input:

Maximum-sum-of-nodes-in-Binary-tree-such-that-no-two-are-adjacent-3

Output: 16
Explanation: The maximum sum is sum of nodes 1 4 5 6 , i.e 16. These nodes are non adjacent.

Maximum-sum-of-nodes-in-Binary-tree-such-that-no-two-are-adjacent-4

Using Recursion – O(2^n) Time and O(n) Space

We can solve this problem by considering the fact that both node and its children can’t be in sum at the same time, so when we take a node into our sum, we will call recursively for its grandchildren or if we don’t take this node then we will call for all its children nodes and finally we will choose maximum from both of the results. 

  • For each node in the binary tree, calculate two sums:
    • Include the current node: Add the current node’s value and the maximum sums of its grandchildren.
    • Exclude the current node: Sum the maximum sums of its left and right children.
  • Use a recursive function to compute these sums for each node.
  • For each node, take the maximum of the two sums (including or excluding the node).
  • The result for the root node is the maximum sum of non-adjacent nodes in the entire tree.
C++
// C++ program to find the maximum sum of 
// non-adjacent nodes in a binary tree.

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;     
    Node *left, *right; 
    
    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Utility method to return the maximum sum 
// rooted at the node 'curr'
int getMaxSumUtil(Node* node) {
    if (node == nullptr) {
      
        // If the node is null, the sum is 0
        return 0;
    }

    // Calculate the maximum sum including the
      // current node
    int incl = node->data;
  
    // If the left child exists, include its contribution
    if (node->left) {
        incl += getMaxSumUtil(node->left->left) + 
                  getMaxSumUtil(node->left->right);
    }
    
    // If the right child exists, include its contribution
    if (node->right) {
          incl += getMaxSumUtil(node->right->left) + 
                  getMaxSumUtil(node->right->right);
    }

    // Calculate the maximum sum excluding 
      // the current node
    int excl = 0;
    if (node->left) {
        excl += getMaxSumUtil(node->left);
    }
    if (node->right) {
        excl += getMaxSumUtil(node->right);
    }

    // The result for the current node is the
      // maximum of including or excluding it
    return max(incl, excl);
}

int getMaxSum(Node* root) {
  
    // If the tree is empty, the maximum sum is 0
    if (root == nullptr) {
        return 0;
    }
    
    // Call the utility function to compute the
      // maximum sum for the entire tree
    return getMaxSumUtil(root);
}

int main() {
  
    // Creating a binary tree with the following structure:
    //          1
    //         / \
    //        2   3
    //       /   / \
    //      1   4   5

    Node* root = new Node(1);           
    root->left = new Node(2);             
    root->right = new Node(3);           
    root->right->left = new Node(4);     
    root->right->right = new Node(5);     
    root->left->left = new Node(1);       

    cout << getMaxSum(root) << endl;
    return 0;
}
Java
// Java program to find the maximum sum 
// of non-adjacent nodes in a binary tree.
import java.util.*;

class Node {
    int data;
    Node left, right;
    
    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Utility method to return the maximum sum 
      // rooted at the node 'node'
    static int getMaxSumUtil(Node node) {
        if (node == null) {
          
            // If the node is null, the sum is 0
            return 0;
        }

        // Calculate the maximum sum including
          // the current node
        int incl = node.data;
        
        // If the left child exists, include its contribution
        if (node.left != null) {
            incl += getMaxSumUtil(node.left.left) + 
                    getMaxSumUtil(node.left.right);
        }
        
        // If the right child exists, include
          // its contribution
        if (node.right != null) {
            incl += getMaxSumUtil(node.right.left) + 
                    getMaxSumUtil(node.right.right);
        }

        // Calculate the maximum sum excluding
          // the current node
        int excl = 0;
        if (node.left != null) {
            excl += getMaxSumUtil(node.left);
        }
        if (node.right != null) {
            excl += getMaxSumUtil(node.right);
        }

        // The result for the current node is the
          // maximum of including or excluding it
        return Math.max(incl, excl);
    }

    static int getMaxSum(Node root) {
      
        // If the tree is empty, the maximum sum is 0
        if (root == null) {
            return 0;
        }
        // Call the utility function to compute the 
          // maximum sum for the entire tree
        return getMaxSumUtil(root);
    }

    public static void main(String[] args) {
      
        // Creating a binary tree with the following structure:
        //          1
        //         / \
        //        2   3
        //       /   / \
        //      1   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(5);
        root.left.left = new Node(1);

        System.out.println(getMaxSum(root));
    }
}
Python
# Python program to find the maximum sum 
# of non-adjacent nodes in a binary tree.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Utility method to return the maximum 
# sum rooted at the node 'node'
def getMaxSumUtil(node):
    if node is None:
      
        # If the node is null, the 
        # sum is 0
        return 0

    # Calculate the maximum sum including
    # the current node
    incl = node.data

    # If the left child exists, include its contribution
    if node.left:
        incl += getMaxSumUtil(node.left.left) + \
                getMaxSumUtil(node.left.right)

    # If the right child exists, include its contribution
    if node.right:
        incl += getMaxSumUtil(node.right.left) + \
                getMaxSumUtil(node.right.right)

    # Calculate the maximum sum excluding the 
    # current node
    excl = 0
    if node.left:
        excl += getMaxSumUtil(node.left)
    if node.right:
        excl += getMaxSumUtil(node.right)

    # The result for the current node is the 
    # maximum of including or excluding it
    return max(incl, excl)

def getMaxSum(root):
  
    # If the tree is empty, the maximum sum is 0
    if root is None:
        return 0
      
    # Call the utility function to compute the
    # maximum sum for the entire tree
    return getMaxSumUtil(root)

# Creating a binary tree with the following structure:
#          1
#         / \
#        2   3
#       /   / \
#      1   4   5
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(5)
root.left.left = Node(1)

print(getMaxSum(root))
C#
// C# program to find the maximum sum 
// of non-adjacent nodes in a binary tree.
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Utility method to return the maximum 
      // sum rooted at the node 'node'
    static int GetMaxSumUtil(Node node) {
        if (node == null) {
          
            // If the node is null, the sum is 0
            return 0;
        }

        // Calculate the maximum sum including
          // the current node
        int incl = node.data;

        // If the left child exists, include its
          // contribution
        if (node.left != null) {
            incl += GetMaxSumUtil(node.left.left) + 
                      GetMaxSumUtil(node.left.right);
        }

        // If the right child exists, include its contribution
        if (node.right != null) {
            incl += GetMaxSumUtil(node.right.left) + 
                      GetMaxSumUtil(node.right.right);
        }

        // Calculate the maximum sum excluding 
          // the current node
        int excl = 0;
        if (node.left != null) {
            excl += GetMaxSumUtil(node.left);
        }
        if (node.right != null) {
            excl += GetMaxSumUtil(node.right);
        }

        // The result for the current node is
          // the maximum of including or excluding it
        return Math.Max(incl, excl);
    }

    static int GetMaxSum(Node root) {
      
        // If the tree is empty, the maximum sum is 0
        if (root == null) {
            return 0;
        }
      
        // Call the utility function to compute 
          // the maximum sum for the entire tree
        return GetMaxSumUtil(root);
    }

    static void Main(string[] args) {
      
        // Creating a binary tree with the following structure:
        //          1
        //         / \
        //        2   3
        //       /   / \
        //      1   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(5);
        root.left.left = new Node(1);

        Console.WriteLine(GetMaxSum(root));
    }
}
JavaScript
// JavaScript program to find the maximum sum
// of non-adjacent nodes in a binary tree.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Utility method to return the maximum sum 
// rooted at the node 'node'
function getMaxSumUtil(node) {
    if (node === null) {
    
        // If the node is null, the sum is 0
        return 0;
    }

    // Calculate the maximum sum including the
    // current node
    let incl = node.data;

    // If the left child exists, include its contribution
    if (node.left) {
        incl += getMaxSumUtil(node.left.left) + 
                getMaxSumUtil(node.left.right);
    }

    // If the right child exists, include its contribution
    if (node.right) {
        incl += getMaxSumUtil(node.right.left) + 
                getMaxSumUtil(node.right.right);
    }

    // Calculate the maximum sum excluding 
    // the current node
    let excl = 0;
    if (node.left) {
        excl += getMaxSumUtil(node.left);
    }
    if (node.right) {
        excl += getMaxSumUtil(node.right);
    }

    // The result for the current node is the 
    // maximum of including or excluding it
    return Math.max(incl, excl);
}

function getMaxSum(root) {

    // If the tree is empty, the maximum sum is 0
    if (root === null) return 0;
    
    // Call the utility function to compute 
    // the maximum sum for the entire tree
    return getMaxSumUtil(root);
}

// Creating a binary tree with the following structure:
//          1
//         / \
//        2   3
//       /   / \
//      1   4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);
root.left.left = new Node(1);

console.log(getMaxSum(root));

Output
11

Using pair – O(n) Time and O(h) Space

Return a pair 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.

C++
// C++ program to find maximum sum in Binary Tree
// such that no two nodes are adjacent.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int d) {
        data = d;
        left = nullptr;
        right = nullptr;
    }
};

pair<int, int> maxSumHelper(Node* root) {
    if (root == nullptr) {
        pair<int, int> sum(0, 0);
        return sum;
    }
    pair<int, int> sum1 = maxSumHelper(root->left);
    pair<int, int> sum2 = maxSumHelper(root->right);
    pair<int, int> sum;

    // This node is included (Left and right children
    // are not included)
    sum.first = sum1.second + sum2.second + root->data;

    // This node is excluded (Either left or right
    // child is included)
    sum.second = max(sum1.first, sum1.second)
                 + max(sum2.first, sum2.second);

    return sum;
}

// Returns maximum sum from subset of nodes
// of binary tree under given constraints
int getMaxSum(Node* root) {
    pair<int, int> res = maxSumHelper(root);
    return max(res.first, res.second);
}

int main() {
  
    // Creating a binary tree with the following structure:
    //          1
    //         / \
    //        2   3
    //       /   / \
    //      1   4   5

    Node* root = new Node(1);           
    root->left = new Node(2);             
    root->right = new Node(3);           
    root->right->left = new Node(4);     
    root->right->right = new Node(5);     
    root->left->left = new Node(1); 
  
      cout << getMaxSum(root);
    return 0;
}
Java
// Java program to find maximum sum in Binary Tree
// such that no two nodes are adjacent.
class Node {
    int data;
    Node left, right;
    Node(int data) {
      
        this.data = data;
        left = right = null;
    }
};

class Pair {
    int first, second;
    Pair(int first, int second) {
        this.first = first;
        this.second = second;
    }
}

class GfG {

    static Pair maxSumHelper(Node root) {
        if (root == null) {
            Pair sum = new Pair(0, 0);
            return sum;
        }
        Pair sum1 = maxSumHelper(root.left);
        Pair sum2 = maxSumHelper(root.right);
        Pair sum = new Pair(0, 0);

        // This node is included (Left and right children
        // are not included)
        sum.first = sum1.second + sum2.second + root.data;

        // This node is excluded (Either left or right
        // child is included)
        sum.second = Math.max(sum1.first, sum1.second)
                     + Math.max(sum2.first, sum2.second);

        return sum;
    }

    // Returns maximum sum from subset of nodes
    // of binary tree under given constraints
    static int getMaxSum(Node root) {
        Pair res = maxSumHelper(root);
        return Math.max(res.first, res.second);
    }

    public static void main(String args[]) {
      
        // Creating a binary tree with the following structure:
        //          1
        //         / \
        //        2   3
        //       /   / \
        //      1   4   5

        Node root = new Node(1);           
        root.left = new Node(2);             
        root.right = new Node(3);           
        root.right.left = new Node(4);     
        root.right.right = new Node(5);     
        root.left.left = new Node(1);   
      
          System.out.print(getMaxSum(root));
      
    }
}
Python
# Python program to find the maximum sum in a Binary Tree
# such that no two nodes are adjacent.

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Helper function to find the maximum sum
def maxSumHelper(root):
    if root is None:
        return (0, 0)
    
    # Recursively get the maximum sum for left
    # and right subtrees
    left_sum = maxSumHelper(root.left)
    right_sum = maxSumHelper(root.right)

    # This node is included (children are not included)
    include = left_sum[1] + right_sum[1] + root.data

    # This node is excluded (children may be included)
    exclude = max(left_sum[0], left_sum[1]) + \
    max(right_sum[0], right_sum[1])

    return (include, exclude)

# Function to get the maximum sum with 
# the given constraints
def getMaxSum(root):
    result = maxSumHelper(root)
    return max(result[0], result[1])

if __name__ == "__main__":
  
    # Creating a binary tree with the following structure:
    #          1
    #         / \
    #        2   3
    #       /   / \
    #      1   4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.right.left = Node(4)
    root.right.right = Node(5)
    root.left.left = Node(1)
    print(getMaxSum(root))
C#
// C# program to find the maximum sum in a Binary Tree
// such that no two nodes are adjacent.
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class GfG {
  
    // Helper function to find the maximum sum
    static (int include, int exclude) MaxSumHelper(Node root) {
        if (root == null)
            return (0, 0);

        // Recursively get the maximum sum for left
          // and right subtrees
        var leftSum = MaxSumHelper(root.left);
        var rightSum = MaxSumHelper(root.right);

        // This node is included (children are
          // not included)
        int include = leftSum.exclude + rightSum.exclude + root.data;

        // This node is excluded (children may be included)
        int exclude = Math.Max(leftSum.include, leftSum.exclude) +
                      Math.Max(rightSum.include, rightSum.exclude);

        return (include, exclude);
    }

    // Function to get the maximum sum with the 
      // given constraints
    static int GetMaxSum(Node root) {
        var result = MaxSumHelper(root);
        return Math.Max(result.include, result.exclude);
    }

    static void Main() {
      
        // Creating a binary tree with the following structure:
        //          1
        //         / \
        //        2   3
        //       /   / \
        //      1   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(5);
        root.left.left = new Node(1);

        Console.WriteLine(GetMaxSum(root));
    }
}
JavaScript
// JavaScript program to find the maximum sum in a Binary Tree
// such that no two nodes are adjacent.

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Helper function to find the maximum sum
function maxSumHelper(root) {
    if (root === null) {
        return [0, 0];
    }

    // Recursively get the maximum sum for left and right subtrees
    const leftSum = maxSumHelper(root.left);
    const rightSum = maxSumHelper(root.right);

    // This node is included (children are not included)
    const include = leftSum[1] + rightSum[1] + root.data;

    // This node is excluded (children may be included)
    const exclude = Math.max(leftSum[0], leftSum[1]) + 
                    Math.max(rightSum[0], rightSum[1]);

    return [include, exclude];
}

// Function to get the maximum sum with the given constraints
function getMaxSum(root) {
    const result = maxSumHelper(root);
    return Math.max(result[0], result[1]);
}

// Creating a binary tree with the following structure:
//          1
//         / \
//        2   3
//       /   / \
//      1   4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);
root.left.left = new Node(1);

console.log(getMaxSum(root));

Output
11

Using Top-Down DP (Memoization) – O(n) Time and O(n) Space

Maximum-sum-of-nodes-in-Binary-tree-such-that-no-two-are-adjacent-5

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

  • 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.
C++
// C++ program to find the maximum sum of 
// non-adjacent nodes in a binary tree using memoization.

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;     
    Node *left, *right; 
    
    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Utility method to return the maximum sum rooted
// at the node 'node'
int getMaxSumUtil(Node* node, unordered_map<Node*, int>& memo) {
    if (node == nullptr) {
      
        // If the node is null, the sum is 0
        return 0;
    }
    
    // If the result is already computed, return it from memo
    if (memo.find(node) != memo.end()) {
        return memo[node];
    }

    // Calculate the maximum sum including the current node
    int incl = node->data;
    
    // If the left child exists, include its grandchildren
    if (node->left) {
        incl += getMaxSumUtil(node->left->left, memo) + 
                getMaxSumUtil(node->left->right, memo);
    }

    // If the right child exists, include its grandchildren
    if (node->right) {
        incl += getMaxSumUtil(node->right->left, memo) + 
                getMaxSumUtil(node->right->right, memo);
    }

    // Calculate the maximum sum excluding the current node
    int excl = getMaxSumUtil(node->left, memo) + 
               getMaxSumUtil(node->right, memo);

    // Store the result in memo and return 
      // the maximum of incl and excl
    memo[node] = max(incl, excl);
    return memo[node];
}

// Function to compute the maximum
// sum of non-adjacent nodes
int getMaxSum(Node* root) {
    unordered_map<Node*, int> memo;
    return getMaxSumUtil(root, memo);
}

int main() {
  
    // Creating a binary tree with the following structure:
    //          1
    //         / \
    //        2   3
    //       /   / \
    //      1   4   5

    Node* root = new Node(1);           
    root->left = new Node(2);             
    root->right = new Node(3);           
    root->right->left = new Node(4);     
    root->right->right = new Node(5);     
    root->left->left = new Node(1);       

    cout << getMaxSum(root) << endl;
    return 0;
}
Java
// Java program to find the maximum sum of 
// non-adjacent nodes in a binary tree using memoization.

import java.util.HashMap;

class Node {
    int data;
    Node left, right;
    
    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Utility method to return the maximum 
      // sum rooted at the node 'node'
    static int getMaxSumUtil(Node node, HashMap<Node, Integer> memo) {
        if (node == null) {
          
            // If the node is null, the sum is 0
            return 0;
        }

        // If the result is already computed, 
          // return it from memo
        if (memo.containsKey(node)) {
            return memo.get(node);
        }

        // Calculate the maximum sum including 
          // the current node
        int incl = node.data;
        
        // If the left child exists, include its grandchildren
        if (node.left != null) {
            incl += getMaxSumUtil(node.left.left, memo) + 
                    getMaxSumUtil(node.left.right, memo);
        }

        // If the right child exists, include 
          // its grandchildren
        if (node.right != null) {
            incl += getMaxSumUtil(node.right.left, memo) + 
                    getMaxSumUtil(node.right.right, memo);
        }

        // Calculate the maximum sum excluding the current node
        int excl = getMaxSumUtil(node.left, memo) + 
                   getMaxSumUtil(node.right, memo);

        // Store the result in memo and return 
        // the maximum of incl and excl
        memo.put(node, Math.max(incl, excl));
        return memo.get(node);
    }

    // Function to compute the maximum sum of
      // non-adjacent nodes
    static int getMaxSum(Node root) {
        HashMap<Node, Integer> memo = new HashMap<>();
        return getMaxSumUtil(root, memo);
    }

    public static void main(String[] args) {
      
        // Creating a binary tree with the following structure:
        //          1
        //         / \
        //        2   3
        //       /   / \
        //      1   4   5

        Node root = new Node(1);           
        root.left = new Node(2);             
        root.right = new Node(3);           
        root.right.left = new Node(4);     
        root.right.right = new Node(5);     
        root.left.left = new Node(1);       

        System.out.println(getMaxSum(root));
    }
}
Python
# Python program to find the maximum sum of 
# non-adjacent nodes in a binary tree using memoization.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Utility method to return the maximum sum rooted 
# at the node 'node'
def getMaxSumUtil(node, memo):
    if node is None:
      
        # If the node is null, the sum is 0
        return 0

    # If the result is already computed, return 
    # it from memo
    if node in memo:
        return memo[node]

    # Calculate the maximum sum including the current node
    incl = node.data

    # If the left child exists, include its grandchildren
    if node.left:
        incl += getMaxSumUtil(node.left.left, memo) + \
                getMaxSumUtil(node.left.right, memo)

    # If the right child exists, include its grandchildren
    if node.right:
        incl += getMaxSumUtil(node.right.left, memo) + \
                getMaxSumUtil(node.right.right, memo)

    # Calculate the maximum sum excluding the current node
    excl = getMaxSumUtil(node.left, memo) + \
           getMaxSumUtil(node.right, memo)

    # Store the result in memo and return 
    memo[node] = max(incl, excl)
    return memo[node]

# Function to compute the maximum sum of
# non-adjacent nodes
def getMaxSum(root):
    memo = {}
    return getMaxSumUtil(root, memo)

# Creating a binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(5)
root.left.left = Node(1)

print(getMaxSum(root))
C#
// C# program to find the maximum sum of 
// non-adjacent nodes in a binary tree using memoization.

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Utility method to return the maximum 
      // sum rooted at the node 'node'
    static int getMaxSumUtil(Node node, Dictionary<Node, int> memo) {
        if (node == null) {
          
            // If the node is null, the sum is 0
            return 0;
        }

        // If the result is already computed,
          // return it from memo
        if (memo.ContainsKey(node)) {
            return memo[node];
        }

        // Calculate the maximum sum including 
          // the current node
        int incl = node.data;

        // If the left child exists, include its
          // grandchildren
        if (node.left != null) {
            incl += getMaxSumUtil(node.left.left, memo) + 
                      getMaxSumUtil(node.left.right, memo);
        }

        // If the right child exists, include 
          // its grandchildren
        if (node.right != null) {
            incl += getMaxSumUtil(node.right.left, memo) + 
                      getMaxSumUtil(node.right.right, memo);
        }

        // Calculate the maximum sum excluding the 
          // current node
        int excl = getMaxSumUtil(node.left, memo) +
                    getMaxSumUtil(node.right, memo);

        // Store the result in memo and return 
        memo[node] = Math.Max(incl, excl);
        return memo[node];
    }

    static int getMaxSum(Node root) {
        Dictionary<Node, int> memo = new Dictionary<Node, int>();
        return getMaxSumUtil(root, memo);
    }

    static void Main() {
      
        // Creating a binary tree with the following structure:
        //          1
        //         / \
        //        2   3
        //       /   / \
        //      1   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.right.left = new Node(4);
        root.right.right = new Node(5);
        root.left.left = new Node(1);

        Console.WriteLine(getMaxSum(root));
    }
}
JavaScript
// JavaScript program to find the maximum sum of 
// non-adjacent nodes in a binary tree using memoization.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Utility method to return the maximum sum
// rooted at the node 'node'
function getMaxSumUtil(node, memo) {
    if (node === null) {
    
        // If the node is null, the sum is 0
        return 0;
    }

    // If the result is already computed, return it from memo
    if (memo.has(node)) {
        return memo.get(node);
    }

    // Calculate the maximum sum including the current node
    let incl = node.data;

    // If the left child exists, include its grandchildren
    if (node.left) {
        incl += getMaxSumUtil(node.left.left, memo) + 
                getMaxSumUtil(node.left.right, memo);
    }

    // If the right child exists, include its grandchildren
    if (node.right) {
        incl += getMaxSumUtil(node.right.left, memo) + 
                getMaxSumUtil(node.right.right, memo);
    }

    // Calculate the maximum sum excluding the 
    // current node
    let excl = getMaxSumUtil(node.left, memo) +
               getMaxSumUtil(node.right, memo);

    // Store the result in memo and return 
    memo.set(node, Math.max(incl, excl));
    return memo.get(node);
}

// Function to compute the maximum sum of
// non-adjacent nodes
function getMaxSum(root) {
    let memo = new Map();
    return getMaxSumUtil(root, memo);
}

// Creating a binary tree with the following structure:
//          1
//         / \
//        2   3
//       /   / \
//      1   4   5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);
root.left.left = new Node(1);

console.log(getMaxSum(root));

Output
11


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg