| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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 sealed class PathSum2DepthFirstSearchOptimized : IPathSum2 |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n) |
| | | 21 | | /// Space complexity - O(n) |
| | | 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 | | var result = new List<IList<int>>(); |
| | 12 | 29 | | var currentPath = new List<int>(); |
| | | 30 | | |
| | 12 | 31 | | PathSum(root, targetSum, currentPath, result); |
| | | 32 | | |
| | 12 | 33 | | return result; |
| | 12 | 34 | | } |
| | | 35 | | |
| | | 36 | | private static void PathSum(TreeNode? root, int targetSum, IList<int> currentPath, ICollection<IList<int>> result) |
| | 126 | 37 | | { |
| | 126 | 38 | | if (root == null) |
| | 60 | 39 | | { |
| | 60 | 40 | | return; |
| | | 41 | | } |
| | | 42 | | |
| | 66 | 43 | | currentPath.Add(root.val); |
| | | 44 | | |
| | 66 | 45 | | if (root.left == null && root.right == null && targetSum == root.val) |
| | 9 | 46 | | { |
| | 9 | 47 | | result.Add(new List<int>(currentPath)); |
| | 9 | 48 | | } |
| | | 49 | | else |
| | 57 | 50 | | { |
| | 57 | 51 | | PathSum(root.left, targetSum - root.val, currentPath, result); |
| | 57 | 52 | | PathSum(root.right, targetSum - root.val, currentPath, result); |
| | 57 | 53 | | } |
| | | 54 | | |
| | 66 | 55 | | currentPath.RemoveAt(currentPath.Count - 1); |
| | 126 | 56 | | } |
| | | 57 | | } |