| | 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 | | using System.Text; |
| | 14 | |
|
| | 15 | | namespace LeetCode.Algorithms.BinaryTreePaths; |
| | 16 | |
|
| | 17 | | /// <inheritdoc /> |
| | 18 | | public class BinaryTreePathsDepthFirstSearch : IBinaryTreePaths |
| | 19 | | { |
| | 20 | | /// <summary> |
| | 21 | | /// Time complexity - O(n) |
| | 22 | | /// Space complexity - O(n * h) |
| | 23 | | /// </summary> |
| | 24 | | /// <param name="root"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public IList<string> BinaryTreePaths(TreeNode? root) |
| 2 | 27 | | { |
| 2 | 28 | | var treePaths = new List<string>(); |
| | 29 | |
|
| 2 | 30 | | BuildTreePaths(root, new StringBuilder(), treePaths); |
| | 31 | |
|
| 2 | 32 | | return treePaths; |
| 2 | 33 | | } |
| | 34 | |
|
| | 35 | | private static void BuildTreePaths(TreeNode? root, StringBuilder pathStringBuilder, IList<string> treePaths) |
| 6 | 36 | | { |
| 6 | 37 | | if (root == null) |
| 1 | 38 | | { |
| 1 | 39 | | return; |
| | 40 | | } |
| | 41 | |
|
| 5 | 42 | | var pathStringBuilderLength = pathStringBuilder.Length; |
| | 43 | |
|
| 5 | 44 | | if (pathStringBuilder.Length > 0) |
| 3 | 45 | | { |
| 3 | 46 | | pathStringBuilder.Append("->"); |
| 3 | 47 | | } |
| | 48 | |
|
| 5 | 49 | | pathStringBuilder.Append(root.val); |
| | 50 | |
|
| 5 | 51 | | if (root.left == null && root.right == null) |
| 3 | 52 | | { |
| 3 | 53 | | treePaths.Add(pathStringBuilder.ToString()); |
| 3 | 54 | | } |
| | 55 | | else |
| 2 | 56 | | { |
| 2 | 57 | | BuildTreePaths(root.left, pathStringBuilder, treePaths); |
| 2 | 58 | | BuildTreePaths(root.right, pathStringBuilder, treePaths); |
| 2 | 59 | | } |
| | 60 | |
|
| 5 | 61 | | pathStringBuilder.Length = pathStringBuilderLength; |
| 6 | 62 | | } |
| | 63 | | } |