| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.PathSum2; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class PathSum2DepthFirstSearch : IPathSum2 |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n log n) |
| | 21 | | /// Space complexity - O(n * h) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <param name="targetSum"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public IList<IList<int>> PathSum(TreeNode? root, int targetSum) |
| 12 | 27 | | { |
| 12 | 28 | | return root == null ? [] : PathSum(new List<int> { root.val }, root, targetSum, root.val); |
| 12 | 29 | | } |
| | 30 | |
|
| | 31 | | private static List<IList<int>> PathSum(IList<int> list, TreeNode root, int targetSum, int currentSum) |
| 66 | 32 | | { |
| 66 | 33 | | var result = new List<IList<int>>(); |
| | 34 | |
|
| 66 | 35 | | if (root.left == null && root.right == null && currentSum == targetSum) |
| 9 | 36 | | { |
| 9 | 37 | | result.Add(list); |
| 9 | 38 | | } |
| | 39 | | else |
| 57 | 40 | | { |
| 57 | 41 | | if (root.left != null) |
| 32 | 42 | | { |
| 32 | 43 | | result.AddRange(PathSum(new List<int>(list) { root.left.val }, root.left, targetSum, |
| 32 | 44 | | currentSum + root.left.val)); |
| 32 | 45 | | } |
| | 46 | |
|
| 57 | 47 | | if (root.right == null) |
| 35 | 48 | | { |
| 35 | 49 | | return result; |
| | 50 | | } |
| | 51 | |
|
| 22 | 52 | | result.AddRange(PathSum(new List<int>(list) { root.right.val }, root.right, targetSum, |
| 22 | 53 | | currentSum + root.right.val)); |
| 22 | 54 | | } |
| | 55 | |
|
| 31 | 56 | | return result; |
| 66 | 57 | | } |
| | 58 | | } |