Maximum Sum Path
Binary Trees
JavaScript
Problem:
Given a binary tree, find the maximum sum path from a leaf to a root.
Algorithm:
- Keep track of
maxSum
and thenodes
array. Thenodes
array will store the nodes that form the maximum sum path. - Traverse the tree, recursively calculating the sum of the left and right subtrees.
- At each node, add the node’s value to the running sum and include the node in the
currentPathNodes
list. - When a leaf node is reached (both
left
andright
children are null), compare the sum of the current path to themaxSum
.- If sum of the current path is greater than the
maxSum
, updatemaxSum
to this new sum. And set thenodes
array tocurrentPathNodes
. - If sum is less than the
maxSum
, remove this leaf from thecurrentPathNodes
(pop the node) and continue traversing the other subtree.
- If sum of the current path is greater than the
- Finally return the
maxSum
andnodes
array representing the path of the maximum sum.
This algorithm recursively explores each path, tracking the sum and nodes involved. When a leaf node is reached, it checks if the current path has a greater sum than the previously recorded maximum. If so, it updates the maximum sum and the corresponding path.
Solution & Visualize:
The animation/visualization below demonstrates how the algorithm works.
Result
Code
Input:
The tree nodes should only contain the numbers or `null` followed by comma
Output:
solution.js
binary-tree.js