Maximum path sum

Given a binary tree, find the maximum path sum.

  • Time: O(N)
  • Space: O(1)
class MaxPathSum {
    int max = 0;

    public int maxPathSum(TreeNode root) {
        max = root == null ? 0 : root.val;
        maxPathSumRe(root);
        return max;
    }

    private int maxPathSumRe(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = Math.max(maxPathSumRe(node.left), 0);
        int right = Math.max(maxPathSumRe(node.right), 0);
        max = Math.max(max, left + right + node.val);
        return node.val + Math.max(left, right);
    }
}

results matching ""

    No results matching ""