题目
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入:[1,2,3]
1
/ \
2 3
输出:6
示例2:
输入:[-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
输出:42
思路
dfs的过程中会经历每个父节点,并计算出经过该父节点的最大路径和,将每个父节点的最大路径和与全局max比较,最终得到整个二叉树的最大路径和
实现
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
public:
int max = 0;
int maxPathSum(TreeNode* root) {
max = root->val;
func(root);
return max;
}
// input : 父节点 output:父节点最大的子树路径(要么是左子树要么是右子树)
// func作用: 深度遍历整个树,将max值逐个与 "每个父节点的最大路径" 做比较,遍历完后即为全局的最大路径
int func(TreeNode* root) {
int tmp = root->val;
int left_child = 0;
if (root->left) {
int a = func(root->left);
if (a > 0) {
left_child = a;
}
}
int right_child = 0;
if (root->right) {
int a = func(root->right);
if (a > 0) {
right_child = a;
}
}
if (root->val + left_child + right_child > max) {
max = root->val + left_child + right_child;
}
return root->val + std::max(left_child, right_child);
}
};