| | | 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.AddOneRowToTree; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class AddOneRowToTreeBreadthFirstSearch : IAddOneRowToTree |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n) |
| | | 21 | | /// Space complexity - O(n) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="root"></param> |
| | | 24 | | /// <param name="val"></param> |
| | | 25 | | /// <param name="depth"></param> |
| | | 26 | | /// <returns></returns> |
| | | 27 | | public TreeNode? AddOneRow(TreeNode? root, int val, int depth) |
| | 15 | 28 | | { |
| | 15 | 29 | | if (root == null) |
| | 1 | 30 | | { |
| | 1 | 31 | | return null; |
| | | 32 | | } |
| | | 33 | | |
| | 14 | 34 | | if (depth == 1) |
| | 2 | 35 | | { |
| | 2 | 36 | | return new TreeNode(val, root); |
| | | 37 | | } |
| | | 38 | | |
| | 12 | 39 | | var queue = new Queue<(TreeNode node, int level)>(); |
| | | 40 | | |
| | 12 | 41 | | queue.Enqueue((root, 1)); |
| | | 42 | | |
| | 52 | 43 | | while (queue.Count > 0) |
| | 40 | 44 | | { |
| | 40 | 45 | | var (treeNode, level) = queue.Dequeue(); |
| | | 46 | | |
| | 40 | 47 | | if (level + 1 == depth) |
| | 14 | 48 | | { |
| | 14 | 49 | | treeNode.left = new TreeNode(val, treeNode.left); |
| | 14 | 50 | | treeNode.right = new TreeNode(val, null, treeNode.right); |
| | 14 | 51 | | } |
| | | 52 | | else |
| | 26 | 53 | | { |
| | 26 | 54 | | level++; |
| | | 55 | | |
| | 26 | 56 | | if (treeNode.left != null) |
| | 20 | 57 | | { |
| | 20 | 58 | | queue.Enqueue((treeNode.left, level)); |
| | 20 | 59 | | } |
| | | 60 | | |
| | 26 | 61 | | if (treeNode.right != null) |
| | 8 | 62 | | { |
| | 8 | 63 | | queue.Enqueue((treeNode.right, level)); |
| | 8 | 64 | | } |
| | 26 | 65 | | } |
| | 40 | 66 | | } |
| | | 67 | | |
| | 12 | 68 | | return root; |
| | 15 | 69 | | } |
| | | 70 | | } |