| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.MaximumDepthOfNaryTree; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class MaximumDepthOfNaryTreeBreadthFirstSearch : IMaximumDepthOfNaryTree |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n) |
| | | 21 | | /// Space complexity - O(w), where w is the width of the tree |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="root"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public int MaxDepth(Node? root) |
| | 3 | 26 | | { |
| | 3 | 27 | | if (root == null) |
| | 1 | 28 | | { |
| | 1 | 29 | | return 0; |
| | | 30 | | } |
| | | 31 | | |
| | 2 | 32 | | var maxDepth = 0; |
| | | 33 | | |
| | 2 | 34 | | var queue = new Queue<(Node Node, int Depth)>(); |
| | | 35 | | |
| | 2 | 36 | | queue.Enqueue((root, 1)); |
| | | 37 | | |
| | 22 | 38 | | while (queue.Count > 0) |
| | 20 | 39 | | { |
| | 20 | 40 | | var (node, depth) = queue.Dequeue(); |
| | | 41 | | |
| | 20 | 42 | | maxDepth = Math.Max(maxDepth, depth); |
| | | 43 | | |
| | 20 | 44 | | if (node.children == null) |
| | 7 | 45 | | { |
| | 7 | 46 | | continue; |
| | | 47 | | } |
| | | 48 | | |
| | 75 | 49 | | foreach (var child in node.children) |
| | 18 | 50 | | { |
| | 18 | 51 | | queue.Enqueue((child, depth + 1)); |
| | 18 | 52 | | } |
| | 13 | 53 | | } |
| | | 54 | | |
| | 2 | 55 | | return maxDepth; |
| | 3 | 56 | | } |
| | | 57 | | } |