commit b375dbd77fd05aaa8a5b621816cb041084cdbdd3
parent ef5380526d0b959417df9972bc1d385ee29c258c
Author: AndrewLockVI <andrewlaack1@gmail.com>
Date: Fri, 21 Apr 2023 01:01:40 -0500
Completed path sum problem using dart
Diffstat:
1 file changed, 30 insertions(+), 0 deletions(-)
diff --git a/path-sum/path-sum.dart b/path-sum/path-sum.dart
@@ -0,0 +1,30 @@
+//Find if there is a path down a binary tree where all of the vals
+//added together is equal to the targetSum.
+//The time complexity of this is O(n) because in the worst case
+//the algorithm will visit all nodes.
+
+
+class Solution {
+ int goal = 0;
+ bool found = false;
+ bool hasPathSum(TreeNode? root, int targetSum) {
+ goal = targetSum;
+ recurse(root, 0);
+ return found;
+ }
+ void recurse(TreeNode? node, int current_val){
+ current_val += node?.val ?? 0;
+ if(node == null){
+ return;
+ }
+ if(found == true){
+ return;
+ }
+ if(current_val == goal && node.left == null && node.right == null){
+ found = true;
+ return;
+ }
+ recurse(node?.left , current_val);
+ recurse(node?.right, current_val);
+ }
+}