用 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

更新時間:2021 年 1 月 27 日

125 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告