| | 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.SumRootToLeafNumbers; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class SumRootToLeafNumbersDepthFirstSearch : ISumRootToLeafNumbers |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) for a skewed tree, O(log n) for a balanced tree |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int SumNumbers(TreeNode? root) |
| 4 | 26 | | { |
| 4 | 27 | | return root == null ? 0 : GetSum(root, 0); |
| 4 | 28 | | } |
| | 29 | |
|
| | 30 | | private static int GetSum(TreeNode treeNode, int currentSum) |
| 11 | 31 | | { |
| 11 | 32 | | currentSum = (currentSum * 10) + treeNode.val; |
| | 33 | |
|
| 11 | 34 | | if (treeNode.left == null && treeNode.right == null) |
| 7 | 35 | | { |
| 7 | 36 | | return currentSum; |
| | 37 | | } |
| | 38 | |
|
| 4 | 39 | | var sum = 0; |
| | 40 | |
|
| 4 | 41 | | if (treeNode.left != null) |
| 4 | 42 | | { |
| 4 | 43 | | sum += GetSum(treeNode.left, currentSum); |
| 4 | 44 | | } |
| | 45 | |
|
| 4 | 46 | | if (treeNode.right != null) |
| 3 | 47 | | { |
| 3 | 48 | | sum += GetSum(treeNode.right, currentSum); |
| 3 | 49 | | } |
| | 50 | |
|
| 4 | 51 | | return sum; |
| 11 | 52 | | } |
| | 53 | | } |