leetcode_cpp/tree/Binary_tree/124/main.cpp
2021-11-11 00:03:12 +08:00

66 lines
1.7 KiB
C++
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @Description:
* @Version: 1.0
* @Autor: zhuyijun
* @Date: 2021-11-10 09:09:12
* @LastEditTime: 2021-11-10 13:21:51
*/
// 路径
// 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。
//同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个
//节点,且不一定经过根节点。
// 路径和 是路径中各节点值的总和。
// 给你一个二叉树的根节点 root ,返回其 最大路径和 。
//  
// 示例 1
// 输入root = [1,2,3]
// 输出6
// 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
// 示例 2
// 输入root = [-10,9,20,null,null,15,7]
// 输出42
// 解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
//  
// 提示:
// 树中节点数目范围是 [1, 3 * 104]
// -1000 <= Node.val <= 1000
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x), left(left), right(right) {}
};
int maxPathSum(TreeNode *root, int &val) {
if (root == nullptr) return 0;
int left = maxPathSum(root->left, val);
int right = maxPathSum(root->right, val);
int lmr = root->val + max(0, left) + max(0, right);
int ret = root->val + max(0, max(left, right));
val = max(val, max(lmr, ret));
return ret;
}
int maxPathSum(TreeNode *root) {
int val = INT_MIN;
maxPathSum(root, val);
return val;
}
int main() {
TreeNode root = TreeNode();
std::cout << maxPathSum(&root);
}