Maximum Sum Level Except Triangular Number in Binary Tree
Last Updated : 23 Jul, 2025
Given a Binary tree, Then the task is to output the maximum sum at any level excluding Triangular numbers. Xth Triangular numbers is the sum of starting X natural numbers, i.e. {1, 3, 6, 10..} are Triangular numbers.
Examples:
Input:
Input Tree
Output: 31
Explanation: The sum at each level excluding Triangular numbers is:
Level 1: 0(1 is a Triangular number)
Level 2: 0 (3 and 6 are Triangular number)
Level 3: 9+22 = 31 (28 and 36 are Triangular numbers)
Level 4: 14 (45 is a Triangular number)
Since, 31 is the maximum sum at 3rd level of tree. Therefore, output is 31.
Input:
Input Tree
Output: 75
Explanation: It can be verified that the maximum sum at any level excluding Triangular numbers will be 75.
Approach 1: Implement the idea below to solve the problem
The problem can be solved using BFS algorithm. Iterate on the nodes at each level of Tree and calculate the sum excluding Triangular numbers. Update the sum at each level with maximum sum and return it after end of BFS.
Identifying a Triangular number: Any number X is triangular, If (8 * X + 1) is a perfect square.
Follow the steps to solve the problem:
Create a variable let say MaxSumLevel to store the maximum sum.
At iteration of each level using BFS follow the below-mentioned steps:
Create a variable let say Sum
If (Current node is not Triangular number), Then add it into Sum.
Push the children of current node Queue.
Update MaxSumLevel as max(MaxLevelSum, Sum)
Return MaxSumLevel.
Below is the implementation for the above approach:
Java
importjava.util.LinkedList;importjava.util.Queue;// Build tree classclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassBinaryTree{// Function to check if a number is triangular// A number is triangular if and only// if 8 * number + 1 is a perfect squarestaticbooleanisTriangular(intnum){inttest=8*num+1;intsqrtTest=(int)Math.sqrt(test);returnsqrtTest*sqrtTest==test;}// Function to find the maximum sum level except// triangular numbers in the binary treestaticinttriangularNumber(Noderoot){// variable to store maximum sum levelintmaxSumLevel=0;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){intsz=q.size();intsum=0;// Processing nodes at the current levelfor(inti=0;i<sz;i++){Nodenode=q.poll();// Checking if the node's data is// triangular add in sum if not// triangular numberif(!isTriangular(node.data)){sum+=node.data;}// Adding child nodes to the queue// for processingif(node.left!=null){q.add(node.left);}if(node.right!=null){q.add(node.right);}}// Updating the maximum sum variablemaxSumLevel=Math.max(maxSumLevel,sum);}returnmaxSumLevel;}// Driver codepublicstaticvoidmain(String[]args){// Example tree creationNoderoot=newNode(2);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(9);root.left.right=newNode(28);root.right.left=newNode(22);root.right.right=newNode(36);root.left.left.right=newNode(45);root.right.right.right=newNode(14);// Finding and displaying triangular numbers at each// level of the treeintans=triangularNumber(root);System.out.println("Maximum sum of level is: "+ans);}}// This code is contributed by shivamgupta0987654321
Python3
# Python Code for above approachimportmath# Build tree classclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to check if a number is triangular# A number is triangular if and only# if 8 * number + 1 is a perfect squaredefisTriangular(num):test=8*num+1sqrtTest=int(math.sqrt(test))returnsqrtTest*sqrtTest==test# Function to find the maximum sum level except# triangular numbers in the binary treedeftriangularNumber(root):# variable to store maximum sum levelmaxSumLevel=0q=[]q.append(root)whilelen(q)>0:sz=len(q)sum_val=0# Processing nodes at the current levelfor_inrange(sz):node=q.pop(0)# Checking if the node's data is# triangular add in sum if not# triangular numberifnotisTriangular(node.data):sum_val+=node.data# Adding child nodes to the queue# for processingifnode.left:q.append(node.left)ifnode.right:q.append(node.right)# Updating the maximum sum variablemaxSumLevel=max(maxSumLevel,sum_val)returnmaxSumLevel# Driver code# Example tree creationroot=Node(2)root.left=Node(3)root.right=Node(6)root.left.left=Node(9)root.left.right=Node(28)root.right.left=Node(22)root.right.right=Node(36)root.left.left.right=Node(45)root.right.right.right=Node(14)# Finding and displaying triangular numbers at each# level of the treeans=triangularNumber(root)print("maximum sum of level is:",ans)
C#
// C# program for the above approachusingSystem;usingSystem.Collections.Generic;// Build tree classclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGFG{// Function to check if a number is triangular// A number is triangular if and only// if 8 * number + 1 is a perfect squarestaticboolIsTriangular(intnum){inttest=8*num+1;intsqrtTest=(int)Math.Sqrt(test);returnsqrtTest*sqrtTest==test;}// Function to find the maximum sum level except// triangular numbers in the binary treestaticintTriangularNumber(Noderoot){// variable to store maximum sum levelintmaxSumLevel=0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){intsz=q.Count;intsum=0;// Processing nodes at the current levelfor(inti=0;i<sz;i++){Nodenode=q.Dequeue();// Checking if the node's data is// triangular add in sum if not// triangular numberif(!IsTriangular(node.data)){sum+=node.data;}// Adding child nodes to the queue// for processingif(node.left!=null){q.Enqueue(node.left);}if(node.right!=null){q.Enqueue(node.right);}}// Updating the maximum sum variablemaxSumLevel=Math.Max(maxSumLevel,sum);}returnmaxSumLevel;}// Driver codestaticvoidMain(){// Example tree creationNoderoot=newNode(2);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(9);root.left.right=newNode(28);root.right.left=newNode(22);root.right.right=newNode(36);root.left.left.right=newNode(45);root.right.right.right=newNode(14);// Finding and displaying triangular numbers at each// level of the treeintans=TriangularNumber(root);Console.WriteLine("Maximum sum of level is: "+ans);}}// This code is contributed by Susobhan Akhuli
JavaScript
// Build tree classclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to check if a number is triangular// A number is triangular if and only// if 8 * number + 1 is a perfect squarefunctionisTriangular(num){consttest=8*num+1;constsqrtTest=Math.sqrt(test);returnNumber.isInteger(sqrtTest);}// Function to find the maximum sum level except// triangular numbers in the binary treefunctiontriangularNumber(root){// Variable to store maximum sum levelletmaxSumLevel=0;constqueue=[];queue.push(root);while(queue.length>0){constsz=queue.length;letsum=0;// Processing nodes at the current levelfor(leti=0;i<sz;i++){constnode=queue.shift();// Checking if the node's data is// triangular add in sum if not// triangular numberif(!isTriangular(node.data)){sum+=node.data;}// Adding child nodes to the queue// for processingif(node.left!==null){queue.push(node.left);}if(node.right!==null){queue.push(node.right);}}// Updating the maximum sum variablemaxSumLevel=Math.max(maxSumLevel,sum);}returnmaxSumLevel;}// Driver code// Example tree creationconstroot=newNode(2);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(9);root.left.right=newNode(28);root.right.left=newNode(22);root.right.right=newNode(36);root.left.left.right=newNode(45);root.right.right.right=newNode(14);// Finding and displaying triangular numbers at each// level of the treeconstans=triangularNumber(root);console.log("Maximum sum of level is: "+ans);
C++14
#include<iostream>#include<cmath>#include<queue>usingnamespacestd;// Build tree classclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=NULL;right=NULL;}};// Function to check if a number is triangular// A number is triangular if and only// if 8 * number + 1 is a perfect squareboolisTriangular(intnum){inttest=8*num+1;intsqrtTest=sqrt(test);returnsqrtTest*sqrtTest==test;}// Function to find the maximum sum level except// triangular numbers in the binary treeinttriangularNumber(Node*root){// variable to store maximum sum levelintmaxSumLevel=0;queue<Node*>q;q.push(root);while(!q.empty()){intsz=q.size();intsum=0;// Processing nodes at the current levelfor(inti=0;i<sz;i++){Node*node=q.front();q.pop();// Checking if the node's data is// triangular add in sum if not// triangular numberif(!isTriangular(node->data)){sum+=node->data;}// Adding child nodes to the queue// for processingif(node->left!=NULL){q.push(node->left);}if(node->right!=NULL){q.push(node->right);}}// Updating the maximum sum variablemaxSumLevel=max(maxSumLevel,sum);}returnmaxSumLevel;}// Driver codeintmain(){// Example tree creationNode*root=newNode(2);root->left=newNode(3);root->right=newNode(6);root->left->left=newNode(9);root->left->right=newNode(28);root->right->left=newNode(22);root->right->right=newNode(36);root->left->left->right=newNode(45);root->right->right->right=newNode(14);// Finding and displaying triangular numbers at each// level of the treeintans=triangularNumber(root);cout<<"maximum sum of level is : "<<ans;return0;}
Output
maximum sum of level is : 31
Time Complexity: O(N), where N is the number of nodes in the given binary tree. Space Complexity: O(N)
Approach 2: Implement the idea below to solve the problem
The problem can be solved by performing a depth-first traversal (DFS) on the binary tree. During the traversal, calculate the sum at each level while excluding triangular numbers. Keep track of the maximum sum encountered. Return the maximum sum after the traversal completes.
Identifying a Triangular number: A number X is triangular if (8 * X + 1) is a perfect square.
Follow the steps to solve the problem:
1. Define a recursive function, let's say findMaxSumLevel, to perform DFS traversal on the binary tree.
2. In the findMaxSumLevel function:
Base case: If the current node is NULL, return.
Initialize the sum at the current level to 0.
If the current node's data is not a triangular number, add it to the sum.
Recursively call findMaxSumLevel for the left and right child nodes, incrementing the level by 1.
3. In the main function:
Create an empty vector, levelSums, to store the sum at each level.
Call findMaxSumLevel with the root node, passing levelSums by reference and starting the level at 0.
Find the maximum sum among the level sums stored in levelSums.
Return the maximum sum.
Below is the implementation for the above approach:
C++
// Nikunj Sonigara#include<iostream>#include<queue>#include<cmath>usingnamespacestd;// Build tree classclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=NULL;right=NULL;}};// Function to check if a number is triangularboolisTriangular(intnum){inttest=8*num+1;intsqrtTest=sqrt(test);returnsqrtTest*sqrtTest==test;}// Recursive function to find maximum sum level excluding triangular numbersvoidfindMaxSumLevel(Node*root,intlevel,vector<int>&levelSums){if(root==NULL)return;if(level>=levelSums.size())levelSums.push_back(0);// Exclude triangular numbers while calculating sum at each levelif(!isTriangular(root->data))levelSums[level]+=root->data;findMaxSumLevel(root->left,level+1,levelSums);findMaxSumLevel(root->right,level+1,levelSums);}// Function to find the maximum sum level except triangular numbers in the binary treeintmaxSumLevelExceptTriangular(Node*root){vector<int>levelSums;findMaxSumLevel(root,0,levelSums);// Find the maximum sumintmaxSum=0;for(intsum:levelSums){maxSum=max(maxSum,sum);}returnmaxSum;}// Driver codeintmain(){// Example tree creationNode*root=newNode(2);root->left=newNode(3);root->right=newNode(6);root->left->left=newNode(9);root->left->right=newNode(28);root->right->left=newNode(22);root->right->right=newNode(36);root->left->left->right=newNode(45);root->right->right->right=newNode(14);// Finding and displaying triangular numbers at each// level of the treeintans=maxSumLevelExceptTriangular(root);cout<<"maximum sum of level is : "<<ans;return0;}
Java
importjava.util.ArrayList;importjava.util.List;importjava.util.Queue;importjava.util.LinkedList;import staticjava.lang.Math.sqrt;// Build tree classclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassMain{// Function to check if a number is triangularpublicstaticbooleanisTriangular(intnum){inttest=8*num+1;intsqrtTest=(int)Math.sqrt(test);returnsqrtTest*sqrtTest==test;}// Recursive function to find maximum sum level excluding triangular numberspublicstaticvoidfindMaxSumLevel(Noderoot,intlevel,List<Integer>levelSums){if(root==null)return;if(level>=levelSums.size())levelSums.add(0);// Exclude triangular numbers while calculating sum at each levelif(!isTriangular(root.data))levelSums.set(level,levelSums.get(level)+root.data);findMaxSumLevel(root.left,level+1,levelSums);findMaxSumLevel(root.right,level+1,levelSums);}// Function to find the maximum sum level except triangular numbers in the binary treepublicstaticintmaxSumLevelExceptTriangular(Noderoot){List<Integer>levelSums=newArrayList<>();findMaxSumLevel(root,0,levelSums);// Find the maximum sumintmaxSum=0;for(intsum:levelSums){maxSum=Math.max(maxSum,sum);}returnmaxSum;}// Driver codepublicstaticvoidmain(String[]args){// Example tree creationNoderoot=newNode(2);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(9);root.left.right=newNode(28);root.right.left=newNode(22);root.right.right=newNode(36);root.left.left.right=newNode(45);root.right.right.right=newNode(14);// Finding and displaying triangular numbers at each// level of the treeintans=maxSumLevelExceptTriangular(root);System.out.println("maximum sum of level is : "+ans);}}
Python3
importmath# Define tree node classclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to check if a number is triangulardefis_triangular(num):test=8*num+1sqrt_test=int(math.sqrt(test))returnsqrt_test*sqrt_test==test# Recursive function to find maximum sum level excluding triangular numbersdeffind_max_sum_level(root,level,level_sums):ifrootisNone:returniflevel>=len(level_sums):level_sums.append(0)# Exclude triangular numbers while calculating sum at each levelifnotis_triangular(root.data):level_sums[level]+=root.datafind_max_sum_level(root.left,level+1,level_sums)find_max_sum_level(root.right,level+1,level_sums)# Function to find the maximum sum level except triangular numbers in the binary treedefmax_sum_level_except_triangular(root):level_sums=[]find_max_sum_level(root,0,level_sums)# Find the maximum summax_sum=max(level_sums)returnmax_sum# Driver codeif__name__=="__main__":# Example tree creationroot=Node(2)root.left=Node(3)root.right=Node(6)root.left.left=Node(9)root.left.right=Node(28)root.right.left=Node(22)root.right.right=Node(36)root.left.left.right=Node(45)root.right.right.right=Node(14)# Finding and displaying triangular numbers at each# level of the treeans=max_sum_level_except_triangular(root)print("maximum sum of level is:",ans)
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to check if a number is triangularfunctionisTriangular(num){lettest=8*num+1;letsqrtTest=Math.sqrt(test);returnMath.floor(sqrtTest)*Math.floor(sqrtTest)===test;}// Recursive function to find maximum sum level excluding triangular numbersfunctionfindMaxSumLevel(root,level,levelSums){if(!root)return;if(level>=levelSums.length)levelSums.push(0);// Exclude triangular numbers while calculating sum at each levelif(!isTriangular(root.data))levelSums[level]+=root.data;findMaxSumLevel(root.left,level+1,levelSums);findMaxSumLevel(root.right,level+1,levelSums);}// Function to find the maximum sum level except triangular numbers in the binary treefunctionmaxSumLevelExceptTriangular(root){letlevelSums=[];findMaxSumLevel(root,0,levelSums);// Find the maximum sumletmaxSum=0;for(letsumoflevelSums){maxSum=Math.max(maxSum,sum);}returnmaxSum;}// Example tree creationletroot=newNode(2);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(9);root.left.right=newNode(28);root.right.left=newNode(22);root.right.right=newNode(36);root.left.left.right=newNode(45);root.right.right.right=newNode(14);// Finding and displaying triangular numbers at each level of the treeletans=maxSumLevelExceptTriangular(root);console.log("Maximum sum of level is:",ans);
Output
maximum sum of level is : 31
Time Complexity: O(N), where N is the number of nodes in the given binary tree.
Space Complexity: O(H), where H is the height of the binary tree.