Share 1207 leetcode c++,

congloc455

New member
#LeetCode #C ++ #1207 #binary-Tree #AlGorithM ## 1207 LeetCode C ++ Solution

** Vấn đề: ** Cho gốc của cây nhị phân, trả lại tổng đường dẫn tối đa.

Một đường dẫn được định nghĩa là một chuỗi các nút trong cây, trong đó mỗi nút được kết nối với nút tiếp theo bằng một cạnh.Tổng đường dẫn là tổng của các giá trị của tất cả các nút trong đường dẫn.

**Ví dụ:**

`` `
Đầu vào: root = [1,2,3]
Đầu ra: 6
Giải thích: Tổng đường dẫn tối đa là 2 + 3 = 5.
`` `

**Giải pháp:**

`` `C ++
#include <bit/stdc ++. H>
sử dụng không gian tên STD;

Nút cấu trúc {
int val;
Nút *trái;
Nút *phải;
};

int maxPathSum (nút* root) {
if (root == nullptr) {
trả lại 0;
}

int leftMax = MaxPathSum (root-> trái);
int rightMax = maxPathSum (root-> right);

// Trả về tổng đường dẫn tối đa bao gồm nút hiện tại.
int MaxPathSumIncludingCienNode = MAX (root-> val, max (leftMax + root-> val, rightmax + root-> val));

// Trả về tổng đường dẫn tối đa không bao gồm nút hiện tại.
int maxPathSumExcludingCienNode = MAX (LeftMax, RightMax);

Trả về MAX (MaxPathSumIncludingCienNode, MaxPathSumExcludingCienNode);
}

int main () {
// Tạo một cây nhị phân.
Nút* root = node new (1);
root-> trái = nút mới (2);
root-> right = node new (3);

// In tổng đường dẫn tối đa.
cout << MaxPathSum (root) << endl;

trả lại 0;
}
`` `

## hashtags

* #LeetCode
* #C ++
* #1207
* #cây nhị phân
* #AlGorithM
=======================================
#LeetCode #C++ #1207 #binary-tree #AlGorithM ## 1207 Leetcode C++ Solution

**Problem:** Given the root of a binary tree, return the maximum path sum.

A path is defined as a sequence of nodes in the tree, where each node is connected to the next node by an edge. The path sum is the sum of the values of all the nodes in the path.

**Example:**

```
Input: root = [1,2,3]
Output: 6
Explanation: The maximum path sum is 2 + 3 = 5.
```

**Solution:**

```c++
#include <bits/stdc++.h>
using namespace std;

struct Node {
int val;
Node *left;
Node *right;
};

int maxPathSum(Node* root) {
if (root == nullptr) {
return 0;
}

int leftMax = maxPathSum(root->left);
int rightMax = maxPathSum(root->right);

// Return the maximum path sum that includes the current node.
int maxPathSumIncludingCurrentNode = max(root->val, max(leftMax + root->val, rightMax + root->val));

// Return the maximum path sum that does not include the current node.
int maxPathSumExcludingCurrentNode = max(leftMax, rightMax);

return max(maxPathSumIncludingCurrentNode, maxPathSumExcludingCurrentNode);
}

int main() {
// Create a binary tree.
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);

// Print the maximum path sum.
cout << maxPathSum(root) << endl;

return 0;
}
```

## Hashtags

* #LeetCode
* #C++
* #1207
* #binary-tree
* #AlGorithM
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top