| | 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.NumberOfGoodLeafNodesPairs; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class NumberOfGoodLeafNodesPairsDepthFirstSearch : INumberOfGoodLeafNodesPairs |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n * d^2) |
| | 21 | | /// Space complexity - O(n * d) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <param name="distance"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public int CountPairs(TreeNode? root, int distance) |
| 3 | 27 | | { |
| 3 | 28 | | var result = 0; |
| | 29 | |
|
| 3 | 30 | | CountPairs(root, distance, ref result); |
| | 31 | |
|
| 3 | 32 | | return result; |
| 3 | 33 | | } |
| | 34 | |
|
| | 35 | | private static List<int> CountPairs(TreeNode? node, int distance, ref int result) |
| 21 | 36 | | { |
| 21 | 37 | | if (node == null) |
| 3 | 38 | | { |
| 3 | 39 | | return []; |
| | 40 | | } |
| | 41 | |
|
| 18 | 42 | | if (node.left == null && node.right == null) |
| 9 | 43 | | { |
| 9 | 44 | | return [1]; |
| | 45 | | } |
| | 46 | |
|
| 9 | 47 | | var leftDistances = CountPairs(node.left, distance, ref result); |
| 9 | 48 | | var rightDistances = CountPairs(node.right, distance, ref result); |
| | 49 | |
|
| 9 | 50 | | result += leftDistances.Sum(leftDistance => |
| 27 | 51 | | rightDistances.Count(rightDistance => leftDistance + rightDistance <= distance)); |
| | 52 | |
|
| 9 | 53 | | var currentDistances = new List<int>(); |
| | 54 | |
|
| 43 | 55 | | foreach (var leftDistance in leftDistances) |
| 8 | 56 | | { |
| 8 | 57 | | if (leftDistance + 1 <= distance) |
| 8 | 58 | | { |
| 8 | 59 | | currentDistances.Add(leftDistance + 1); |
| 8 | 60 | | } |
| 8 | 61 | | } |
| | 62 | |
|
| 47 | 63 | | foreach (var rightDistance in rightDistances) |
| 10 | 64 | | { |
| 10 | 65 | | if (rightDistance + 1 <= distance) |
| 9 | 66 | | { |
| 9 | 67 | | currentDistances.Add(rightDistance + 1); |
| 9 | 68 | | } |
| 10 | 69 | | } |
| | 70 | |
|
| 9 | 71 | | return currentDistances; |
| 21 | 72 | | } |
| | 73 | | } |