| | 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.BalancedBinaryTree; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class BalancedBinaryTreeDepthFirstSearch : IBalancedBinaryTree |
| | 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 bool IsBalanced(TreeNode? root) |
| 7 | 26 | | { |
| 7 | 27 | | return root == null || IsBalanced(root, out _); |
| 7 | 28 | | } |
| | 29 | |
|
| | 30 | | private static bool IsBalanced(TreeNode? root, out int height) |
| 74 | 31 | | { |
| 74 | 32 | | if (root == null) |
| 40 | 33 | | { |
| 40 | 34 | | height = 0; |
| | 35 | |
|
| 40 | 36 | | return true; |
| | 37 | | } |
| | 38 | |
|
| 34 | 39 | | var leftIsBalanced = IsBalanced(root.left, out var leftHeight); |
| 34 | 40 | | var rightIsBalanced = IsBalanced(root.right, out var rightHeight); |
| | 41 | |
|
| 34 | 42 | | height = 1 + Math.Max(leftHeight, rightHeight); |
| | 43 | |
|
| 34 | 44 | | if (!leftIsBalanced || !rightIsBalanced) |
| 1 | 45 | | { |
| 1 | 46 | | return false; |
| | 47 | | } |
| | 48 | |
|
| 33 | 49 | | return Math.Abs(leftHeight - rightHeight) <= 1; |
| 74 | 50 | | } |
| | 51 | | } |