LeetCode - 2196
January 1, 2026
LeetCode 2196
Solution
Analyze descriptions:
- Node values are unique and can be used as keys
- A Hash Table can be used to build node relationships and retrieve nodes
Analyze numeric constraints:
- max(parenti, childi) <= 10^5
- descriptions.length <= 10^4
Performance trade-off:
- Based on practical experience, when the value range is within an order of tens relative to the number of entries, an Array can be used instead of a Hash Table to achieve better performance
Code
java
public TreeNode createBinaryTree(int[][] descriptions) {
int maxVal = 0;
for (int[] d : descriptions) {
maxVal = Math.max(maxVal, Math.max(d[0], d[1]));
}
TreeNode[] nodes = new TreeNode[maxVal + 1];
boolean[] isChild = new boolean[maxVal + 1];
for (int[] d : descriptions) {
int parentVal = d[0];
int childVal = d[1];
boolean isLeft = d[2] == 1;
if (nodes[parentVal] == null) {
nodes[parentVal] = new TreeNode(parentVal);
}
if (nodes[childVal] == null) {
nodes[childVal] = new TreeNode(childVal);
}
if (isLeft) {
nodes[parentVal].left = nodes[childVal];
} else {
nodes[parentVal].right = nodes[childVal];
}
isChild[childVal] = true;
}
for (int i = 1; i <= maxVal; i++) {
if (nodes[i] != null && !isChild[i]) {
return nodes[i];
}
}
return null;
}