Problem
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
1 |
|
Return:
1 |
|
Explanation
-
We can use recusive backtracking to solve this, so we create a helper function and pass a temp list and result list as the parameters besides the root node and sum.
-
Inside the helper function, the base case is if the root node is NULL, we just return nothing. Then, we add the current root node’s value to the temp list.
-
Then we check if the current node’s value equal to the sum and also there’s no left and right node, then we add temp list to the result list.
-
Next, we recrusively call the helper function with the left and right child nodes with the updated
sum=sum-root.val
. Then, we should remove the last element of the temp list in order to backtract to the parent node.
Solution
1 |
|