路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

    路径和 是路径中各节点值的总和。

    给你一个二叉树的根节点 root ,返回其 最大路径和 。
    image.png

    1. class Solution {
    2. int maxRes = Integer.MIN_VALUE;
    3. public int maxPathSum(TreeNode root) {
    4. helper(root);
    5. return maxRest;
    6. }
    7. public int helper (root) {
    8. if (root == null)
    9. return 0;
    10. int left = Math.max(helper(root.left), 0);
    11. int right = Math.max(helper(root.right), 0);
    12. maxRes = root.val + left + right;
    13. return root.val + Math.max(left , right);
    14. }
    15. }



    image.png

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum