题目 链接
二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
示例
解题思路
- 从整体出发,要求最大路径和就是要遍历树中的每一个节点,求出该节点所在子树的最大路径和,同时设置变量res判断当前节点的最大路径和是否超出最大值res,超出则更新。
- 怎么求当前节点的最大值?
当前节点的最大路径: max(自己,自己+左边,自己+右边,自己 + 左边 + 右边)
当前节点作为子节点时的贡献:max(自己,自己+左边,自己+右边)
最大值更新的是:当前节点的最大路径
最后返回的是:当前节点作为子节点时的贡献
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return res;
}
int dfs(TreeNode root) {
if(root == null) return 0;
int t = root.val;
int left = dfs(root.left);
int right = dfs(root.right);
if(left >= 0) t += left;
if(right >= 0) t += right;
res = Math.max(res, t);
return Math.max(root.val, Math.max(left, right) + root.val);
}
}