Path Sum
Binary Trees
JavaScript
Problem:
Given a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
Algorithm:
- Keep track of
nodes
array to store the nodes that form the path with the target sum. Use a flagexists
to indicate whether a valid path exists or not. - Traverse the binary tree and perform the following operations:
- At each node, add the node’s value to the running sum.
- When a leaf node is reached (both
left
andright
children are null), check if the running sum is equal totargetSum
.- If the sum is equal to
targetSum
, the current path is the answer. Return the nodes along with the valueTRUE
for theexists
flag. - If the sum does not equal to
targetSum
, remove the current leaf node fromnodes
list and continue traversal.
- If the sum is equal to
- Finally, return the
exists
flag andnodes
array representing the path that sums to the targetSum.
This algorithm traverses the binary tree, calculating the sum of nodes along the path. When a leaf node is reached, it checks if the accumulated sum equals the target sum. If it does, it returns the path; if not, it continues traversing the other branches. The process is repeated until a valid path is found or all paths have been explored.
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