LeetCode每日一题:二叉树最大路径和

问题描述

Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/
2 3

Return6.

问题分析

这题可以看成在树中求最大子数组的大小
对于一个节点,它的最大路径长度是它的左子树路径(如果大于0)+它的右子树路径(如果大于0)+它本身,我们可以根据这个条件来写递归

代码实现

public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        ArrayList result = new ArrayList<>();
        result.add(Integer.MIN_VALUE);
        getMaxPathSum(root, result);
        return result.get(0);
    }

    private int getMaxPathSum(TreeNode node, ArrayList result) {
        if (node == null) return 0;
        int left = Math.max(0, getMaxPathSum(node.left, result));
        int right = Math.max(0, getMaxPathSum(node.right, result));
        result.set(0, Math.max(result.get(0), node.val + left + right));
        return Math.max(left, right) + node.val;
    }

你可能感兴趣的:(LeetCode每日一题:二叉树最大路径和)