| | | 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 AddOneRowToTreeDepthFirstSearch : IAddOneRowToTree |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(n), where n is the number of nodes in the tree |
| | | 21 | | /// Space complexity - O(h), where h is the height of the tree |
| | | 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 | | AddOneRow(root, val, depth, 1); |
| | | 40 | | |
| | 12 | 41 | | return root; |
| | 15 | 42 | | } |
| | | 43 | | |
| | | 44 | | private static void AddOneRow(TreeNode treeNode, int val, int depth, int level) |
| | 40 | 45 | | { |
| | 40 | 46 | | if (level + 1 == depth) |
| | 14 | 47 | | { |
| | 14 | 48 | | treeNode.left = new TreeNode(val, treeNode.left); |
| | 14 | 49 | | treeNode.right = new TreeNode(val, null, treeNode.right); |
| | 14 | 50 | | } |
| | | 51 | | else |
| | 26 | 52 | | { |
| | 26 | 53 | | level++; |
| | | 54 | | |
| | 26 | 55 | | if (treeNode.left != null) |
| | 20 | 56 | | { |
| | 20 | 57 | | AddOneRow(treeNode.left, val, depth, level); |
| | 20 | 58 | | } |
| | | 59 | | |
| | 26 | 60 | | if (treeNode.right != null) |
| | 8 | 61 | | { |
| | 8 | 62 | | AddOneRow(treeNode.right, val, depth, level); |
| | 8 | 63 | | } |
| | 26 | 64 | | } |
| | 40 | 65 | | } |
| | | 66 | | } |