Maximum sum from a tree with adjacent levels not allowed in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a binary tree consisting of positive numbers. Our task is to create a program to find the Maximum sum from a tree with adjacent levels not allowed in C++.

Code Description

Here, we will find the maximum sum of node of the tree in such a way that the sum does not contain nodes from two adjacent levels of the tree.

Let’s take an example to understand the problem,

Output

21

Explanation

Taking root as starting level, sum = 5 + 3 + 8 + 1 = 17 Taking sub-child of root as starting level, sum = 2 + 6 + 9 + 4 = 21

Solution Approach

To find the maxSum, one condition is the no adjacent elements. For this, we will take one sum set from root node(Level 1) and another from child node(Level 2). The next sum nodes will be extracted from the current node by finding the grandchildren nodes.

For this, we will recursively find maxSum value and then the maximum sum value for sum starting from level 1 or level 2 will be the resultant maxSum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include<bits/stdc++.h>
using namespace std;
struct Node{
   int data;
   Node* left, *right;
   Node(int item){
      data = item;
   }
};
int getMaxSum(Node* root) ;
int findSumFromNode(Node* root){
   if (root == NULL)
      return 0;
      int sum = root->data;
   if (root->left != NULL){
      sum += getMaxSum(root->left->left);
      sum += getMaxSum(root->left->right);
   }
   if (root->right != NULL){
      sum += getMaxSum(root->right->left);
      sum += getMaxSum(root->right->right);
   }
   return sum;
}
int getMaxSum(Node* root){
   if (root == NULL)
      return 0;
      return max(findSumFromNode(root), (findSumFromNode(root->left) + findSumFromNode(root->right)));
}
int main(){
   Node* root = new Node(5);
   root->left = new Node(2);
   root->right = new Node(10);
   root->left->left = new Node(4);
   root->left->right = new Node(6);
   root->right->right = new Node(9);
   cout<<"The maximum sum from a tree with adjacent levels not allowed is "<<getMaxSum(root);
   return 0;
}

Output

The maximum sum from a tree with adjacent levels not allowed is 24
raja
Published on 22-Jul-2020 11:43:21
Advertisements