| | 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.SmallestStringStartingFromLeaf; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class SmallestStringStartingFromLeafDepthFirstSearch : ISmallestStringStartingFromLeaf |
| | 18 | | { |
| | 19 | | private string? _smallestString; |
| | 20 | |
|
| | 21 | | /// <summary> |
| | 22 | | /// Time complexity - O(n) for a balanced tree, O(n^2) for a skewed tree |
| | 23 | | /// Space complexity - O(n) |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="root"></param> |
| | 26 | | /// <returns></returns> |
| | 27 | | public string? SmallestFromLeaf(TreeNode? root) |
| 3 | 28 | | { |
| 3 | 29 | | FindSmallest(root, string.Empty); |
| | 30 | |
|
| 3 | 31 | | return _smallestString; |
| 3 | 32 | | } |
| | 33 | |
|
| | 34 | | private void FindSmallest(TreeNode? node, string currentPath) |
| 43 | 35 | | { |
| 43 | 36 | | if (node == null) |
| 23 | 37 | | { |
| 23 | 38 | | return; |
| | 39 | | } |
| | 40 | |
|
| 20 | 41 | | var currentChar = (char)('a' + node.val); |
| 20 | 42 | | var newPath = currentChar + currentPath; |
| | 43 | |
|
| 20 | 44 | | if (node.left == null && node.right == null) |
| 10 | 45 | | { |
| 10 | 46 | | if (_smallestString == null || string.CompareOrdinal(newPath, _smallestString) < 0) |
| 5 | 47 | | { |
| 5 | 48 | | _smallestString = newPath; |
| 5 | 49 | | } |
| 10 | 50 | | } |
| | 51 | |
|
| 20 | 52 | | FindSmallest(node.left, newPath); |
| 20 | 53 | | FindSmallest(node.right, newPath); |
| 43 | 54 | | } |
| | 55 | | } |