| | 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.CountCompleteTreeNodes; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class CountCompleteTreeNodesDepthRecursive : ICountCompleteTreeNodes |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(log 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 CountNodes(TreeNode? root) |
| 12 | 26 | | { |
| 12 | 27 | | if (root == null) |
| 3 | 28 | | { |
| 3 | 29 | | return 0; |
| | 30 | | } |
| | 31 | |
|
| 9 | 32 | | var leftDepth = GetDepth(root, true); |
| 9 | 33 | | var rightDepth = GetDepth(root, false); |
| | 34 | |
|
| 9 | 35 | | if (leftDepth == rightDepth) |
| 5 | 36 | | { |
| 5 | 37 | | return (1 << leftDepth) - 1; |
| | 38 | | } |
| | 39 | |
|
| 4 | 40 | | return CountNodes(root.left) + CountNodes(root.right) + 1; |
| 12 | 41 | | } |
| | 42 | |
|
| | 43 | | private static int GetDepth(TreeNode? node, bool left) |
| 18 | 44 | | { |
| 18 | 45 | | var depth = 0; |
| | 46 | |
|
| 46 | 47 | | while (node != null) |
| 28 | 48 | | { |
| 28 | 49 | | depth++; |
| | 50 | |
|
| 28 | 51 | | node = left ? node.left : node.right; |
| 28 | 52 | | } |
| | 53 | |
|
| 18 | 54 | | return depth; |
| 18 | 55 | | } |
| | 56 | | } |