| | 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.CreateBinaryTreeFromDescriptions; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class CreateBinaryTreeFromDescriptionsDictionary : ICreateBinaryTreeFromDescriptions |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="descriptions"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public TreeNode? CreateBinaryTree(int[][] descriptions) |
| 2 | 26 | | { |
| 2 | 27 | | var nodeMap = new Dictionary<int, TreeNode>(); |
| 2 | 28 | | var children = new HashSet<int>(); |
| | 29 | |
|
| 22 | 30 | | foreach (var description in descriptions) |
| 8 | 31 | | { |
| 8 | 32 | | var parentValue = description[0]; |
| 8 | 33 | | var childValue = description[1]; |
| 8 | 34 | | var isLeft = description[2] == 1; |
| | 35 | |
|
| 8 | 36 | | if (!nodeMap.ContainsKey(parentValue)) |
| 3 | 37 | | { |
| 3 | 38 | | nodeMap[parentValue] = new TreeNode(parentValue); |
| 3 | 39 | | } |
| | 40 | |
|
| 8 | 41 | | if (!nodeMap.ContainsKey(childValue)) |
| 7 | 42 | | { |
| 7 | 43 | | nodeMap[childValue] = new TreeNode(childValue); |
| 7 | 44 | | } |
| | 45 | |
|
| 8 | 46 | | var parent = nodeMap[parentValue]; |
| 8 | 47 | | var child = nodeMap[childValue]; |
| | 48 | |
|
| 8 | 49 | | if (isLeft) |
| 5 | 50 | | { |
| 5 | 51 | | parent.left = child; |
| 5 | 52 | | } |
| | 53 | | else |
| 3 | 54 | | { |
| 3 | 55 | | parent.right = child; |
| 3 | 56 | | } |
| | 57 | |
|
| 8 | 58 | | children.Add(childValue); |
| 8 | 59 | | } |
| | 60 | |
|
| 14 | 61 | | foreach (var key in nodeMap.Keys) |
| 5 | 62 | | { |
| 5 | 63 | | if (!children.Contains(key)) |
| 2 | 64 | | { |
| 2 | 65 | | return nodeMap[key]; |
| | 66 | | } |
| 3 | 67 | | } |
| | 68 | |
|
| 0 | 69 | | return null; |
| 2 | 70 | | } |
| | 71 | | } |