Open In App

Maximum Sum Level Except Triangular Number in Binary Tree

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

T1

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:

T2

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
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;
}

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

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads