Sponsored
Sponsored
This approach uses a hash map to create nodes and establish their parent-child relationships. The root node is determined by finding nodes that haven't been a child in any relationship.
Time Complexity: O(N), where N is the number of descriptions.
Space Complexity: O(V), where V is the number of unique nodes.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5 public int val;
6 public TreeNode left;
7 public TreeNode right;
8 public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) {
9 this.val = val;
10 this.left = left;
11 this.right = right;
12 }
13}
14
15public class Solution {
16 public TreeNode CreateBinaryTree(int[][] descriptions) {
17 Dictionary<int, TreeNode> nodeMap = new Dictionary<int, TreeNode>();
18 HashSet<int> children = new HashSet<int>();
19
20 foreach (var desc in descriptions) {
21 int parent = desc[0], child = desc[1], isLeft = desc[2];
22 if (!nodeMap.ContainsKey(parent)) {
23 nodeMap[parent] = new TreeNode(parent);
24 }
25 if (!nodeMap.ContainsKey(child)) {
26 nodeMap[child] = new TreeNode(child);
27 }
28
29 if (isLeft == 1) {
30 nodeMap[parent].left = nodeMap[child];
31 } else {
32 nodeMap[parent].right = nodeMap[child];
33 }
34
35 children.Add(child);
36 }
37
38 foreach (var key in nodeMap.Keys) {
39 if (!children.Contains(key)) {
40 return nodeMap[key];
41 }
42 }
43
44 return null;
45 }
46}
47
The C# solution also uses a dictionary to manage TreeNode instances and a hash set to record child nodes. It iterates through the input descriptions to create and link the nodes, eventually identifying the root node as the one not listed as any child.
This approach uses a two-pass algorithm: the first pass creates all nodes independently, and the second pass links them based on the descriptive relationships. This avoids simultaneous creation and linking, providing a clearer separation of concerns between node creation and linkage.
Time Complexity: O(N), where N is the number of descriptions.
Space Complexity: O(V), where V is the number of unique nodes.
1
The JavaScript implementation follows a similar approach by creating each necessary TreeNode object in advance. Nodes are linked by iterating over the description input, resulting in correct binary tree construction.