C++ 二叉樹中最大父子和


在本教程中,我們將討論一個程式,用於查詢二叉樹中的最大父父子和

為此,我們將使用一棵二叉樹。我們的任務是將父節點與其子節點相加,最後找出所有這些節點的最大值並將其打印出來。

示例

 線上演示

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node *left, *right;
};
//inserting nodes
struct Node* newNode(int n) {
   struct Node* root = new Node();
   root->data = n;
   root->left = root->right = NULL;
   return root;
}
int maxSum(struct Node* root) {
   if (root == NULL)
      return 0;
   int res = maxSum(root->left);
   if (root->left != NULL && root->right != NULL) {
      int sum = root->data + root->left->data + root->right->data;
      res = max(res, sum);
   }
   return max(res, maxSum(root->right));
}
int main() {
   struct Node* root = newNode(15);
   root->left = newNode(16);
   root->left->left = newNode(8);
   root->left->left->left = newNode(55);
   root->left->right = newNode(67);
   root->left->right->left = newNode(44);
   root->right = newNode(17);
   root->right->left = newNode(7);
   root->right->left->right = newNode(11);
   root->right->right = newNode(41);
   cout << maxSum(root);
   return 0;
}

輸出

91

更新時間: 2020-9-09

182 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.