Share leetcode 953 c++,

tansinhstandard

New member
#LeetCode, #C ++, #953, #binarytree, #DFS ## LeetCode 953 C ++: Cho một cây nhị phân, tìm 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:
1
/ \
2 3

Đầu ra: 6

Giải trình:
Đường dẫn có tổng tối đa là 2 -> 1 -> 3, với tổng 6.
`` `

**Giải pháp:**

`` `C ++
#include <Istream>
#include <Vector>

sử dụng không gian tên STD;

struct treende {
int val;
Treende *trái;
Treenode *phải;
Treende (int x): val (x), trái (null), phải (null) {}
};

int maxPathSum (treenode *root) {
int maxsum = int_min;
người trợ giúp (root, maxsum);
trả lại maxsum;
}

int helper (treenode *root, int & maxsum) {
if (root == null) {
trả lại 0;
}

int leftsum = helper (root-> trái, maxsum);
int Landsum = người trợ giúp (root-> right, maxsum);

// Đường dẫn có tổng tối đa đi qua nút gốc.
int pathsum = root-> val + leftsum + bản quyền;
MaxSum = Max (MaxSum, Pathsum);

// Đường dẫn có tổng tối đa không đi qua nút gốc.
int norootpathsum = max (leftsum, bản quyền);

trả lại norootpathsum;
}

int main () {
Treende *root = new treende (1);
root-> left = new treende (2);
root-> right = new treende (3);

cout << MaxPathSum (root) << endl;

trả lại 0;
}
`` `

## hashtags

* #LeetCode
* #C ++
* #953
* #cây nhị phân
* #DFS
=======================================
#LeetCode, #C++, #953, #binarytree, #DFS ## Leetcode 953 C++: Given a binary tree, find 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:
1
/ \
2 3

Output: 6

Explanation:
The path with the maximum sum is 2 -> 1 -> 3, with a sum of 6.
```

**Solution:**

```c++
#include <iostream>
#include <vector>

using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int maxPathSum(TreeNode *root) {
int maxSum = INT_MIN;
helper(root, maxSum);
return maxSum;
}

int helper(TreeNode *root, int &maxSum) {
if (root == NULL) {
return 0;
}

int leftSum = helper(root->left, maxSum);
int rightSum = helper(root->right, maxSum);

// The path with the maximum sum goes through the root node.
int pathSum = root->val + leftSum + rightSum;
maxSum = max(maxSum, pathSum);

// The path with the maximum sum does not go through the root node.
int noRootPathSum = max(leftSum, rightSum);

return noRootPathSum;
}

int main() {
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);

cout << maxPathSum(root) << endl;

return 0;
}
```

## Hashtags

* #LeetCode
* #C++
* #953
* #binarytree
* #DFS
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top