| | 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.NaryTreeLevelOrderTraversal; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class NaryTreeLevelOrderTraversalBreadthFirstSearch : INaryTreeLevelOrderTraversal |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public IList<IList<int>> LevelOrder(Node? root) |
| 3 | 26 | | { |
| 3 | 27 | | if (root == null) |
| 1 | 28 | | { |
| 1 | 29 | | return []; |
| | 30 | | } |
| | 31 | |
|
| 2 | 32 | | var result = new List<IList<int>>(); |
| | 33 | |
|
| 2 | 34 | | var currentLevelNodes = new Queue<Node>(); |
| | 35 | |
|
| 2 | 36 | | currentLevelNodes.Enqueue(root); |
| | 37 | |
|
| 10 | 38 | | while (currentLevelNodes.Count > 0) |
| 8 | 39 | | { |
| 8 | 40 | | var levelValues = new List<int>(); |
| | 41 | |
|
| 8 | 42 | | var nextLevelNodes = new Queue<Node>(); |
| | 43 | |
|
| 28 | 44 | | while (currentLevelNodes.Count > 0) |
| 20 | 45 | | { |
| 20 | 46 | | var currentNode = currentLevelNodes.Dequeue(); |
| | 47 | |
|
| 20 | 48 | | levelValues.Add(currentNode.val); |
| | 49 | |
|
| 20 | 50 | | if (currentNode.children == null) |
| 7 | 51 | | { |
| 7 | 52 | | continue; |
| | 53 | | } |
| | 54 | |
|
| 75 | 55 | | foreach (var child in currentNode.children) |
| 18 | 56 | | { |
| 18 | 57 | | nextLevelNodes.Enqueue(child); |
| 18 | 58 | | } |
| 13 | 59 | | } |
| | 60 | |
|
| 8 | 61 | | result.Add(levelValues); |
| | 62 | |
|
| 8 | 63 | | currentLevelNodes = nextLevelNodes; |
| 8 | 64 | | } |
| | 65 | |
|
| 2 | 66 | | return result; |
| 3 | 67 | | } |
| | 68 | | } |