| | | 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.NaryTreePreorderTraversal; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class NaryTreePreorderTraversalStack : INaryTreePreorderTraversal |
| | | 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<int> Preorder(Node? root) |
| | 2 | 26 | | { |
| | 2 | 27 | | if (root == null) |
| | 0 | 28 | | { |
| | 0 | 29 | | return new List<int>(); |
| | | 30 | | } |
| | | 31 | | |
| | 2 | 32 | | var result = new List<int>(); |
| | | 33 | | |
| | 2 | 34 | | var stack = new Stack<Node>(); |
| | | 35 | | |
| | 2 | 36 | | stack.Push(root); |
| | | 37 | | |
| | 22 | 38 | | while (stack.Count > 0) |
| | 20 | 39 | | { |
| | 20 | 40 | | var node = stack.Pop(); |
| | | 41 | | |
| | 20 | 42 | | result.Add(node.val); |
| | | 43 | | |
| | 20 | 44 | | if (node.children == null) |
| | 7 | 45 | | { |
| | 7 | 46 | | continue; |
| | | 47 | | } |
| | | 48 | | |
| | 62 | 49 | | for (var i = node.children.Count - 1; i >= 0; i--) |
| | 18 | 50 | | { |
| | 18 | 51 | | stack.Push(node.children[i]); |
| | 18 | 52 | | } |
| | 13 | 53 | | } |
| | | 54 | | |
| | 2 | 55 | | return result; |
| | 2 | 56 | | } |
| | | 57 | | } |