| | 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.DiameterOfBinaryTree; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class DiameterOfBinaryTreeDepthFirst : IDiameterOfBinaryTree |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(log n) for a balanced tree, O(n) for a skewed tree |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int DiameterOfBinaryTree(TreeNode? root) |
| 3 | 26 | | { |
| 3 | 27 | | if (root == null) |
| 1 | 28 | | { |
| 1 | 29 | | return 0; |
| | 30 | | } |
| | 31 | |
|
| 2 | 32 | | var maxDiameter = 0; |
| | 33 | |
|
| 2 | 34 | | GetMaxDepth(root, ref maxDiameter); |
| | 35 | |
|
| 2 | 36 | | return maxDiameter; |
| 3 | 37 | | } |
| | 38 | |
|
| | 39 | | private static int GetMaxDepth(TreeNode node, ref int maxDiameter) |
| 7 | 40 | | { |
| 7 | 41 | | var leftDepth = 0; |
| | 42 | |
|
| 7 | 43 | | if (node.left != null) |
| 3 | 44 | | { |
| 3 | 45 | | leftDepth = GetMaxDepth(node.left, ref maxDiameter); |
| 3 | 46 | | } |
| | 47 | |
|
| 7 | 48 | | var rightDepth = 0; |
| | 49 | |
|
| 7 | 50 | | if (node.right != null) |
| 2 | 51 | | { |
| 2 | 52 | | rightDepth = GetMaxDepth(node.right, ref maxDiameter); |
| 2 | 53 | | } |
| | 54 | |
|
| 7 | 55 | | maxDiameter = Math.Max(maxDiameter, leftDepth + rightDepth); |
| | 56 | |
|
| 7 | 57 | | return Math.Max(leftDepth, rightDepth) + 1; |
| 7 | 58 | | } |
| | 59 | | } |