Skip to content

Commit 786c6a4

Browse files
committed
Rollback unnecessary changes
1 parent 99812c6 commit 786c6a4

1 file changed

Lines changed: 70 additions & 2 deletions

File tree

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,77 @@
11
import java.util.ArrayList;
2+
import java.util.Comparator;
23

34
class BuildTree {
45

56
static TreeNode buildTree(ArrayList<Record> records) throws InvalidRecordsException {
6-
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
7+
records.sort(Comparator.comparing(Record::recordId));
8+
ArrayList<Integer> orderedRecordIds = new ArrayList<>();
9+
10+
for (Record record : records) {
11+
orderedRecordIds.add(record.recordId());
12+
}
13+
14+
if (records.size() > 0) {
15+
if (orderedRecordIds.get(orderedRecordIds.size() - 1) != orderedRecordIds.size() - 1) {
16+
// Matches non-continuous records or missing items in the sequence
17+
throw new InvalidRecordsException("record id is invalid or out of order");
18+
}
19+
if (orderedRecordIds.get(0) != 0) {
20+
// Matches cases where the root (ID 0) is missing
21+
throw new InvalidRecordsException("record id is invalid or out of order");
22+
}
23+
}
24+
25+
ArrayList<TreeNode> treeNodes = new ArrayList<>();
26+
27+
for (int i = 0; i < orderedRecordIds.size(); i++) {
28+
for (Record record : records) {
29+
if (orderedRecordIds.get(i) == record.recordId()) {
30+
if (record.recordId() == 0 && record.parentId() != 0) {
31+
// Specifically matches "root node has parent"
32+
throw new InvalidRecordsException("node parent_id should be smaller than its record_id");
33+
}
34+
if (record.recordId() < record.parentId()) {
35+
// Matches "higher id parent of lower id"
36+
throw new InvalidRecordsException("record id is invalid or out of order");
37+
}
38+
if (record.recordId() == record.parentId() && record.recordId() != 0) {
39+
// Matches "cycle directly"
40+
throw new InvalidRecordsException("record id is invalid or out of order");
41+
}
42+
treeNodes.add(new TreeNode(record.recordId()));
43+
}
44+
}
45+
}
46+
47+
for (int i = 0; i < orderedRecordIds.size(); i++) {
48+
TreeNode parent;
49+
for (TreeNode n : treeNodes) {
50+
if (i == n.getNodeId()) {
51+
parent = n;
52+
for (Record record : records) {
53+
if (record.parentId() == i) {
54+
for (TreeNode node : treeNodes) {
55+
if (node.getNodeId() == 0) {
56+
continue;
57+
}
58+
if (record.recordId() == node.getNodeId()) {
59+
parent.getChildren().add(node);
60+
}
61+
}
62+
}
63+
}
64+
break;
65+
}
66+
}
67+
68+
}
69+
70+
if (treeNodes.size() > 0) {
71+
return treeNodes.get(0);
72+
}
73+
74+
return null;
775
}
876

9-
}
77+
}

0 commit comments

Comments
 (0)