| | 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.InvertBinaryTree; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class InvertBinaryTreeDepthFirstSearchRecursive : IInvertBinaryTree |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(h), where h is the height of the tree |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public TreeNode? InvertTree(TreeNode? root) |
| 55 | 26 | | { |
| 55 | 27 | | if (root == null) |
| 31 | 28 | | { |
| 31 | 29 | | return null; |
| | 30 | | } |
| | 31 | |
|
| 24 | 32 | | Invert(root); |
| | 33 | |
|
| 24 | 34 | | return root; |
| 55 | 35 | | } |
| | 36 | |
|
| | 37 | | private void Invert(TreeNode? root) |
| 24 | 38 | | { |
| 24 | 39 | | if (root == null) |
| 0 | 40 | | { |
| 0 | 41 | | return; |
| | 42 | | } |
| | 43 | |
|
| 24 | 44 | | (root.left, root.right) = (root.right, root.left); |
| | 45 | |
|
| 24 | 46 | | InvertTree(root.left); |
| 24 | 47 | | InvertTree(root.right); |
| 24 | 48 | | } |
| | 49 | | } |