একটি বাইনারি ট্রি দেওয়া আছে। প্রতিটি লেভেলে নন-লিফ নোডগুলোর সাম বের করে সকল লেভেলের মধ্যে ম্যাক্সিমাম সাম প্রিন্ট করতে হবে।
উদাহরণ ট্রি:
আউটপুট: ৯
ব্যাখ্যা: লেভেল ১: ৪, লেভেল ২: ১+২=৩, লেভেল ৩: ৯ (৪,৭ লিফ নোড), লেভেল ৪: ০। ম্যাক্সিমাম = ৯।
সমাধান: লেভেল অর্ডার ট্রাভার্সাল (BFS) করিয়ে প্রতিটি লেভেলে নন-লিফ নোড (যে নোডের লেফট বা রাইট চাইল্ড আছে) সাম করব। maxSum মেইন্টেইন করব।
উদাহরণ
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
int maxLevelSum(struct Node* root){
if (root == NULL) return 0;
int maxSum = root->data;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int count = q.size();
int levelSum = 0;
while (count--) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL || temp->right != NULL)
levelSum = levelSum + temp->data;
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
}
maxSum = max(levelSum, maxSum);
}
return maxSum;
}
struct Node* insertNode(int data) {
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int main() {
struct Node* root = insertNode(6);
root->left = insertNode(1);
root->right = insertNode(2);
root->left->left = insertNode(4);
root->left->right = insertNode(7);
root->right->right = insertNode(9);
root->right->right->left = insertNode(5);
cout << "The maximum sum of all non-lead nodes at a level of the binary tree is " << maxLevelSum(root);
return 0;
}
আউটপুট
The maximum sum of all non-lead nodes at a level of the binary tree is 9