124. 二叉树中的最大路径和

2021-08-28  本文已影响0人  justonemoretry
image.png

解法

/**
 * 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 {

    public int maxRes = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        getMaxLen(root);
        return maxRes;
    }

    public int getMaxLen(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 获取左右子树上能获取的最大值,负数不取,当0
        int left = Math.max(getMaxLen(root.left), 0);
        int right = Math.max(getMaxLen(root.right), 0);
        int len = left + right + root.val;
        maxRes = Math.max(len, maxRes);
        // 向上联通时,只能取单边,因为每个节点只能经过一次
        return root.val + Math.max(left, right);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读