FastPrepBinary Tree Maximum Path Sum

Binary Tree Maximum Path Sum

Goldman Sachs logoGoldman Sachs● HardFULLTIMEONSITE INTERVIEW

Updated

Problem statement

Given the root of a non-empty binary tree whose nodes contain integers, return the maximum sum of a non-empty path.

A path is a sequence of distinct nodes where consecutive nodes share an edge. The path may start and end at any nodes and does not need to pass through the root. A node may appear at most once in the path.

Function

maxPathSum(root: TreeNode) → int

Examples

Example 1

root = [1,2,3]return = 6
root
123

The path 2 -> 1 -> 3 has sum 6.

Example 2

root = [-10,9,20,null,null,15,7]return = 42
root
-10920157

The best path is 15 -> 20 -> 7, whose sum is 42.

Example 3

root = [-3]return = -3
root
-3

A path must contain at least one node, so the single node is the answer.

Constraints

  • The tree contains between 1 and 5000 nodes.
  • Each node value is between -1000 and 1000.
  • The tree height is at most 1000.

More Goldman Sachs Onsite Interview questions

Similar questions at other companies

All Goldman Sachs interview questionsSee Goldman Sachs hiring insights
Saved
/**
 * 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 maxPathSum(TreeNode root) {
        // Write your code here.
    }
}
Checking account…