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 TreeOutput: 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 TreeOutput: 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
import java.util.LinkedList;
import java.util.Queue;
// Build tree class
class Node {
public int data;
public Node left;
public Node right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
public class BinaryTree {
// Function to check if a number is triangular
// A number is triangular if and only
// if 8 * number + 1 is a perfect square
static boolean isTriangular(int num) {
int test = 8 * num + 1;
int sqrtTest = (int) Math.sqrt(test);
return sqrtTest * sqrtTest == test;
}
// Function to find the maximum sum level except
// triangular numbers in the binary tree
static int triangularNumber(Node root) {
// variable to store maximum sum level
int maxSumLevel = 0;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int sz = q.size();
int sum = 0;
// Processing nodes at the current level
for (int i = 0; i < sz; i++) {
Node node = q.poll();
// Checking if the node's data is
// triangular add in sum if not
// triangular number
if (!isTriangular(node.data)) {
sum += node.data;
}
// Adding child nodes to the queue
// for processing
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
}
// Updating the maximum sum variable
maxSumLevel = Math.max(maxSumLevel, sum);
}
return maxSumLevel;
}
// Driver code
public static void main(String[] args) {
// Example tree creation
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(9);
root.left.right = new Node(28);
root.right.left = new Node(22);
root.right.right = new Node(36);
root.left.left.right = new Node(45);
root.right.right.right = new Node(14);
// Finding and displaying triangular numbers at each
// level of the tree
int ans = triangularNumber(root);
System.out.println("Maximum sum of level is: " + ans);
}
}
// This code is contributed by shivamgupta0987654321
Python3
# Python Code for above approach
import math
# Build tree class
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if a number is triangular
# A number is triangular if and only
# if 8 * number + 1 is a perfect square
def isTriangular(num):
test = 8 * num + 1
sqrtTest = int(math.sqrt(test))
return sqrtTest * sqrtTest == test
# Function to find the maximum sum level except
# triangular numbers in the binary tree
def triangularNumber(root):
# variable to store maximum sum level
maxSumLevel = 0
q = []
q.append(root)
while len(q) > 0:
sz = len(q)
sum_val = 0
# Processing nodes at the current level
for _ in range(sz):
node = q.pop(0)
# Checking if the node's data is
# triangular add in sum if not
# triangular number
if not isTriangular(node.data):
sum_val += node.data
# Adding child nodes to the queue
# for processing
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
# Updating the maximum sum variable
maxSumLevel = max(maxSumLevel, sum_val)
return maxSumLevel
# Driver code
# Example tree creation
root = 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 tree
ans = triangularNumber(root)
print("maximum sum of level is:", ans)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
// Build tree class
class Node {
public int data;
public Node left;
public Node right;
public Node(int val)
{
data = val;
left = null;
right = null;
}
}
public class GFG {
// Function to check if a number is triangular
// A number is triangular if and only
// if 8 * number + 1 is a perfect square
static bool IsTriangular(int num)
{
int test = 8 * num + 1;
int sqrtTest = (int)Math.Sqrt(test);
return sqrtTest * sqrtTest == test;
}
// Function to find the maximum sum level except
// triangular numbers in the binary tree
static int TriangularNumber(Node root)
{
// variable to store maximum sum level
int maxSumLevel = 0;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
int sz = q.Count;
int sum = 0;
// Processing nodes at the current level
for (int i = 0; i < sz; i++) {
Node node = q.Dequeue();
// Checking if the node's data is
// triangular add in sum if not
// triangular number
if (!IsTriangular(node.data)) {
sum += node.data;
}
// Adding child nodes to the queue
// for processing
if (node.left != null) {
q.Enqueue(node.left);
}
if (node.right != null) {
q.Enqueue(node.right);
}
}
// Updating the maximum sum variable
maxSumLevel = Math.Max(maxSumLevel, sum);
}
return maxSumLevel;
}
// Driver code
static void Main()
{
// Example tree creation
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(9);
root.left.right = new Node(28);
root.right.left = new Node(22);
root.right.right = new Node(36);
root.left.left.right = new Node(45);
root.right.right.right = new Node(14);
// Finding and displaying triangular numbers at each
// level of the tree
int ans = TriangularNumber(root);
Console.WriteLine("Maximum sum of level is: "
+ ans);
}
}
// This code is contributed by Susobhan Akhuli
JavaScript
// Build tree class
class Node {
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 square
function isTriangular(num) {
const test = 8 * num + 1;
const sqrtTest = Math.sqrt(test);
return Number.isInteger(sqrtTest);
}
// Function to find the maximum sum level except
// triangular numbers in the binary tree
function triangularNumber(root) {
// Variable to store maximum sum level
let maxSumLevel = 0;
const queue = [];
queue.push(root);
while (queue.length > 0) {
const sz = queue.length;
let sum = 0;
// Processing nodes at the current level
for (let i = 0; i < sz; i++) {
const node = queue.shift();
// Checking if the node's data is
// triangular add in sum if not
// triangular number
if (!isTriangular(node.data)) {
sum += node.data;
}
// Adding child nodes to the queue
// for processing
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
// Updating the maximum sum variable
maxSumLevel = Math.max(maxSumLevel, sum);
}
return maxSumLevel;
}
// Driver code
// Example tree creation
const root = new Node(2);
root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(9);
root.left.right = new Node(28);
root.right.left = new Node(22);
root.right.right = new Node(36);
root.left.left.right = new Node(45);
root.right.right.right = new Node(14);
// Finding and displaying triangular numbers at each
// level of the tree
const ans = triangularNumber(root);
console.log("Maximum sum of level is: " + ans);
C++14
#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
// Build tree class
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val)
{
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 square
bool isTriangular(int num)
{
int test = 8 * num + 1;
int sqrtTest = sqrt(test);
return sqrtTest * sqrtTest == test;
}
// Function to find the maximum sum level except
// triangular numbers in the binary tree
int triangularNumber(Node* root)
{
// variable to store maximum sum level
int maxSumLevel = 0;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
int sum = 0;
// Processing nodes at the current level
for (int i = 0; i < sz; i++) {
Node* node = q.front();
q.pop();
// Checking if the node's data is
// triangular add in sum if not
// triangular number
if (!isTriangular(node->data)) {
sum += node->data;
}
// Adding child nodes to the queue
// for processing
if (node->left != NULL) {
q.push(node->left);
}
if (node->right != NULL) {
q.push(node->right);
}
}
// Updating the maximum sum variable
maxSumLevel = max(maxSumLevel, sum);
}
return maxSumLevel;
}
// Driver code
int main()
{
// Example tree creation
Node* root = new Node(2);
root->left = new Node(3);
root->right = new Node(6);
root->left->left = new Node(9);
root->left->right = new Node(28);
root->right->left = new Node(22);
root->right->right = new Node(36);
root->left->left->right = new Node(45);
root->right->right->right = new Node(14);
// Finding and displaying triangular numbers at each
// level of the tree
int ans = triangularNumber(root);
cout << "maximum sum of level is : " << ans;
return 0;
}
Outputmaximum 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>
using namespace std;
// Build tree class
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
// Function to check if a number is triangular
bool isTriangular(int num) {
int test = 8 * num + 1;
int sqrtTest = sqrt(test);
return sqrtTest * sqrtTest == test;
}
// Recursive function to find maximum sum level excluding triangular numbers
void findMaxSumLevel(Node* root, int level, vector<int>& levelSums) {
if (root == NULL)
return;
if (level >= levelSums.size())
levelSums.push_back(0);
// Exclude triangular numbers while calculating sum at each level
if (!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 tree
int maxSumLevelExceptTriangular(Node* root) {
vector<int> levelSums;
findMaxSumLevel(root, 0, levelSums);
// Find the maximum sum
int maxSum = 0;
for (int sum : levelSums) {
maxSum = max(maxSum, sum);
}
return maxSum;
}
// Driver code
int main() {
// Example tree creation
Node* root = new Node(2);
root->left = new Node(3);
root->right = new Node(6);
root->left->left = new Node(9);
root->left->right = new Node(28);
root->right->left = new Node(22);
root->right->right = new Node(36);
root->left->left->right = new Node(45);
root->right->right->right = new Node(14);
// Finding and displaying triangular numbers at each
// level of the tree
int ans = maxSumLevelExceptTriangular(root);
cout << "maximum sum of level is : " << ans;
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.LinkedList;
import static java.lang.Math.sqrt;
// Build tree class
class Node {
public int data;
public Node left;
public Node right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
public class Main {
// Function to check if a number is triangular
public static boolean isTriangular(int num) {
int test = 8 * num + 1;
int sqrtTest = (int) Math.sqrt(test);
return sqrtTest * sqrtTest == test;
}
// Recursive function to find maximum sum level excluding triangular numbers
public static void findMaxSumLevel(Node root, int level, List<Integer> levelSums) {
if (root == null)
return;
if (level >= levelSums.size())
levelSums.add(0);
// Exclude triangular numbers while calculating sum at each level
if (!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 tree
public static int maxSumLevelExceptTriangular(Node root) {
List<Integer> levelSums = new ArrayList<>();
findMaxSumLevel(root, 0, levelSums);
// Find the maximum sum
int maxSum = 0;
for (int sum : levelSums) {
maxSum = Math.max(maxSum, sum);
}
return maxSum;
}
// Driver code
public static void main(String[] args) {
// Example tree creation
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(9);
root.left.right = new Node(28);
root.right.left = new Node(22);
root.right.right = new Node(36);
root.left.left.right = new Node(45);
root.right.right.right = new Node(14);
// Finding and displaying triangular numbers at each
// level of the tree
int ans = maxSumLevelExceptTriangular(root);
System.out.println("maximum sum of level is : " + ans);
}
}
Python3
import math
# Define tree node class
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if a number is triangular
def is_triangular(num):
test = 8 * num + 1
sqrt_test = int(math.sqrt(test))
return sqrt_test * sqrt_test == test
# Recursive function to find maximum sum level excluding triangular numbers
def find_max_sum_level(root, level, level_sums):
if root is None:
return
if level >= len(level_sums):
level_sums.append(0)
# Exclude triangular numbers while calculating sum at each level
if not is_triangular(root.data):
level_sums[level] += root.data
find_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 tree
def max_sum_level_except_triangular(root):
level_sums = []
find_max_sum_level(root, 0, level_sums)
# Find the maximum sum
max_sum = max(level_sums)
return max_sum
# Driver code
if __name__ == "__main__":
# Example tree creation
root = 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 tree
ans = max_sum_level_except_triangular(root)
print("maximum sum of level is:", ans)
JavaScript
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to check if a number is triangular
function isTriangular(num) {
let test = 8 * num + 1;
let sqrtTest = Math.sqrt(test);
return Math.floor(sqrtTest) * Math.floor(sqrtTest) === test;
}
// Recursive function to find maximum sum level excluding triangular numbers
function findMaxSumLevel(root, level, levelSums) {
if (!root) return;
if (level >= levelSums.length)
levelSums.push(0);
// Exclude triangular numbers while calculating sum at each level
if (!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 tree
function maxSumLevelExceptTriangular(root) {
let levelSums = [];
findMaxSumLevel(root, 0, levelSums);
// Find the maximum sum
let maxSum = 0;
for (let sum of levelSums) {
maxSum = Math.max(maxSum, sum);
}
return maxSum;
}
// Example tree creation
let root = new Node(2);
root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(9);
root.left.right = new Node(28);
root.right.left = new Node(22);
root.right.right = new Node(36);
root.left.left.right = new Node(45);
root.right.right.right = new Node(14);
// Finding and displaying triangular numbers at each level of the tree
let ans = maxSumLevelExceptTriangular(root);
console.log("Maximum sum of level is:", ans);
Outputmaximum 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem