Created
March 9, 2024 12:54
-
-
Save karu19961j/4281c7452113a541ffb4c6284fbac606 to your computer and use it in GitHub Desktop.
path sum 3 solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 pathSum(TreeNode root, int targetSum) { | |
return getSubTress(root, targetSum, new ArrayList<>()); | |
} | |
public int getSubTress(TreeNode root, long targetSum, List<Integer> path) { | |
if (root == null) return 0; | |
path.add(root.val); | |
int pathCount = 0; | |
long sum = 0; | |
for (int i = path.size() - 1; i >= 0; i--) { | |
sum += path.get(i); | |
if (sum == targetSum) pathCount += 1; | |
} | |
pathCount += getSubTress(root.left, targetSum, path); | |
pathCount += getSubTress(root.right, targetSum, path); | |
path.remove(path.size() - 1); | |
return pathCount; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment