LeetCode124: 二叉树中的最大路径和

2020-02-24  本文已影响0人  啊啊啊哼哼哼

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

   1
  / \
 2   3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

输出: 42

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

解题思路:

public class MaxPathSum {
    static int result = -0x3f3f3f3f;

    public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return root.val;
        result = -0x3f3f3f3f;
        dfs(root);
        return result;
    }

    private int dfs(TreeNode root) {
        if (root.left == null && root.right == null) return root.val;
        int leftValue = 0;
        int rightValue = 0;
        if (root.left != null) {
            leftValue = dfs(root.left);
            result = Math.max(leftValue, result);
        }
        if (root.right != null) {
            rightValue = dfs(root.right);
            result = Math.max(rightValue, result);
        }
        //定义sum是因为路径不能重复,因此如果当前点要是想和上一级点连接,就只能取leftValue + root.val 或者rightValue + root.val或者root.val
        int sum = rightValue + root.val + leftValue;
        root.val = Math.max(Math.max(rightValue + root.val, root.val), leftValue + root.val);
        result = Math.max(result,sum);
        return root.val;
    }

    public static void main(String[] args) {

    }
}
上一篇 下一篇

猜你喜欢

热点阅读