Created
September 24, 2022 09:03
-
-
Save dluciano/a7b5621dc41fb69194cd7cc88e9f0f95 to your computer and use it in GitHub Desktop.
113. Path Sum II
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 { | |
* public int val; | |
* public TreeNode left; | |
* public TreeNode right; | |
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public IList<IList<int>> PathSum(TreeNode root, int targetSum) { | |
var currentSum = 0; | |
var currentNodes = new List<int>(); | |
var ans = new List<IList<int>>(); | |
void Traverse(in TreeNode node){ | |
if(node is null) | |
return; | |
currentSum += node.val; | |
currentNodes.Add(node.val); | |
Traverse(node.left); | |
Traverse(node.right); | |
if(node.left is null && node.right is null && currentSum == targetSum) | |
ans.Add(new List<int>(currentNodes)); | |
if(currentNodes.Count > 0) | |
currentNodes.RemoveAt(currentNodes.Count - 1); | |
currentSum -= node.val; | |
} | |
Traverse(root); | |
return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment