From 5f6ae62c62c593cc2bbde232eb3e3d122adaf172 Mon Sep 17 00:00:00 2001 From: fartem Date: Thu, 16 Feb 2023 07:46:17 +0300 Subject: [PATCH] 2023-02-16 update: added "112. Path Sum" --- README.md | 1 + lib/easy/path_sum.dart | 19 ++++++++++ test/easy/path_sum_test.dart | 67 ++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 lib/easy/path_sum.dart create mode 100644 test/easy/path_sum_test.dart diff --git a/README.md b/README.md index 89c311d..bd4aca3 100644 --- a/README.md +++ b/README.md @@ -36,3 +36,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 108. Convert Sorted Array to Binary Search Tree | [Link](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [Link](./lib/easy/convert_sorted_array_to_binary_search_tree.dart) | | 110. Balanced Binary Tree | [Link](https://leetcode.com/problems/balanced-binary-tree/) | [Link](./lib/easy/balanced_binary_tree.dart) | | 111. Minimum Depth of Binary Tree | [Link](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | [Link](./lib/easy/minimum_depth_of_binary_tree.dart) | +| 112. Path Sum | [Link](https://leetcode.com/problems/path-sum/) | [Link](./lib/easy/path_sum.dart) | diff --git a/lib/easy/path_sum.dart b/lib/easy/path_sum.dart new file mode 100644 index 0000000..a73d63e --- /dev/null +++ b/lib/easy/path_sum.dart @@ -0,0 +1,19 @@ +import '../common/tree_node.dart'; + +// https://leetcode.com/problems/path-sum/ +class Solution { + bool hasPathSum(TreeNode? root, int targetSum) { + return _sum(root, targetSum, 0); + } + + bool _sum(TreeNode? node, int targetSum, int count) { + if (node != null) { + if (node.left == null && node.right == null) { + return node.val + count == targetSum; + } + return _sum(node.left, targetSum, node.val + count) || + _sum(node.right, targetSum, node.val + count); + } + return false; + } +} diff --git a/test/easy/path_sum_test.dart b/test/easy/path_sum_test.dart new file mode 100644 index 0000000..38b91aa --- /dev/null +++ b/test/easy/path_sum_test.dart @@ -0,0 +1,67 @@ +import 'package:leetcode_dart/common/tree_node.dart'; +import 'package:leetcode_dart/easy/path_sum.dart'; +import 'package:test/test.dart'; + +void main() { + group( + 'Example tests', + () { + final ps = Solution(); + test( + 'true', + () => expect( + true, + ps.hasPathSum( + TreeNode( + 5, + TreeNode( + 4, + TreeNode( + 11, + TreeNode(7), + TreeNode(2), + ), + null), + TreeNode( + 8, + TreeNode( + 13, + TreeNode( + 4, + TreeNode(1), + null, + ), + ), + ), + ), + 22, + ), + ), + ); + test( + 'false', + () => expect( + false, + ps.hasPathSum( + TreeNode( + 1, + TreeNode(2), + TreeNode(3), + ), + 5, + ), + ), + ); + test( + 'false', + () => expect( + false, + ps.hasPathSum( + null, + 0, + ), + ), + ); + }, + ); +}