用 C++ 在二叉树中找到最大层和
在这个问题中,我们得到了一个带有正值和负值的二叉树。我们的任务是在二叉树中找到最大层和。
问题描述:我们有一棵二叉树,我们将找到二叉树中所有层的总和,然后返回它们的最大值。
我们举一个例子来理解这个问题,
输入:

输出:5
说明:
第一层元素和:3
第二层元素和:-3 + 4 = 1
第三层元素和:5 - 1 + 6 - 5 = 5
解决方案方法
为了解决这个问题,我们需要使用层次遍历来遍历这棵树。对于每一层,我们将找到总和,然后找到最大层和。
一个程序来说明我们解决方案的工作原理,
示例
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode(int data){
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int findMaxLevelSum(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();
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;
}
int main(){
struct Node* root = newNode(3);
root->left = newNode(-3);
root->right = newNode(4);
root->left->left = newNode(5);
root->left->right = newNode(-1);
root->right->left = newNode(6);
root->right->right = newNode(-5);
cout<<"The sum of level with maximum level sum is "<<findMaxLevelSum(root);
return 0;
}输出
The sum of level with maximum level sum is 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP