A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
Example 1:
Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Example 2:
Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
Constraints:
[1, 3 * 104].-1000 <= Node.val <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the maximum path sum in a tree using the brute force approach, you systematically examine every single possible path that connects any two nodes. By checking every combination of connected nodes, you calculate their total sum and keep track of the highest one found.
Here's how the algorithm would work step-by-step:
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.val = value
self.left = left
self.right = right
def max_path_sum_brute_force(root):
if not root:
return 0
def collect_all_nodes(current_node, node_list):
if not current_node:
return
node_list.append(current_node)
collect_all_nodes(current_node.left, node_list)
collect_all_nodes(current_node.right, node_list)
def find_all_paths(current_node, adjacency_list, current_path, all_paths):
current_path.append(current_node)
all_paths.append(list(current_path))
for neighbor in adjacency_list[current_node]:
if neighbor not in current_path:
find_all_paths(neighbor, adjacency_list, current_path, all_paths)
current_path.pop()
tree_nodes = []
collect_all_nodes(root, tree_nodes)
adjacency_list = {node: [] for node in tree_nodes}
def build_graph(current_node):
if not current_node:
return
if current_node.left:
adjacency_list[current_node].append(current_node.left)
adjacency_list[current_node.left].append(current_node)
build_graph(current_node.left)
if current_node.right:
adjacency_list[current_node].append(current_node.right)
adjacency_list[current_node.right].append(current_node)
build_graph(current_node.right)
build_graph(root)
# Generate every single valid sequence of connected nodes because brute force requires checking all
all_possible_paths = []
for start_node in tree_nodes:
find_all_paths(start_node, adjacency_list, [], all_possible_paths)
maximum_sum_found = float('-inf')
# Iterate through every path to compute its total sum and track the highest value encountered
for path_sequence in all_possible_paths:
current_path_sum = sum(node.val for node in path_sequence)
if current_path_sum > maximum_sum_found:
maximum_sum_found = current_path_sum
# Return the highest sum discovered across all exhaustive path combinations
return maximum_sum_foundTo find the most valuable continuous path through a branching tree of numbers, we can visit every junction and calculate the best possible score that can be made by combining the left and right paths. By passing the best single-side score upward while simultaneously checking if a complete peak path is formed at every point, we can find the absolute maximum score in a single pass.
Here's how the algorithm would work step-by-step:
class Solution:
def maxPathSum(self, root_node) -> int:
maximum_path_sum = float('-inf')
def calculate_gain(current_node):
nonlocal maximum_path_sum
if not current_node:
return 0
# Negative paths are ignored since they reduce the overall sum.
left_branch_gain = max(calculate_gain(current_node.left), 0)
right_branch_gain = max(calculate_gain(current_node.right), 0)
# A peak path uses both left and right branches through current node.
current_peak_path = current_node.val + left_branch_gain + right_branch_gain
maximum_path_sum = max(maximum_path_sum, current_peak_path)
# Only the best single side can be passed up to the parent junction.
return current_node.val + max(left_branch_gain, right_branch_gain)
calculate_gain(root_node)
return maximum_path_sum| Case | How to Handle |
|---|---|
| Null root pointer representing an empty tree | Return zero or a special null sentinel value, though the problem states the tree is non-empty. |
| Binary tree with a single node containing a negative value | The recursive DFS will return the negative value itself as the maximum path sum without adding child contributions. |
| Binary tree with all negative node values | Initializing the global maximum to negative infinity ensures we correctly track the single least negative node. |
| Deeply skewed or degenerate binary tree resembling a linked list | Recursion depth reaches N which may cause a stack overflow in languages without tail-call optimization. |
| Path that does not pass through the root node | Computing the local maximum at every node allows any subtree to act as the turning point for a valid path. |
| Node values near the integer minimum or maximum boundaries | Using standard integer types might cause arithmetic overflow when summing large paths, requiring careful constraint handling. |
| Paths where extending to a child yields a negative sum | Taking the maximum of zero and the child path sum effectively discards unprofitable subtrees. |