|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Comparator; |
| 3 | + |
| 4 | +class BuildTree { |
| 5 | + |
| 6 | + TreeNode buildTree(ArrayList<Record> records) throws InvalidRecordsException { |
| 7 | + records.sort(Comparator.comparing(Record::getRecordId)); |
| 8 | + ArrayList<Integer> orderedRecordIds = new ArrayList<>(); |
| 9 | + |
| 10 | + for (Record record : records) { |
| 11 | + orderedRecordIds.add(record.getRecordId()); |
| 12 | + } |
| 13 | + |
| 14 | + if (records.size() > 0) { |
| 15 | + if (orderedRecordIds.get(orderedRecordIds.size() - 1) != orderedRecordIds.size() - 1) { |
| 16 | + throw new InvalidRecordsException("Invalid Records"); |
| 17 | + } |
| 18 | + if (orderedRecordIds.get(0) != 0) { |
| 19 | + throw new InvalidRecordsException("Invalid Records"); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + ArrayList<TreeNode> treeNodes = new ArrayList<>(); |
| 24 | + |
| 25 | + for (int i = 0; i < orderedRecordIds.size(); i++) { |
| 26 | + for (Record record : records) { |
| 27 | + if (orderedRecordIds.get(i) == record.getRecordId()) { |
| 28 | + if (record.getRecordId() == 0 && record.getParentId() != 0) { |
| 29 | + throw new InvalidRecordsException("Invalid Records"); |
| 30 | + } |
| 31 | + if (record.getRecordId() < record.getParentId()) { |
| 32 | + throw new InvalidRecordsException("Invalid Records"); |
| 33 | + } |
| 34 | + if (record.getRecordId() == record.getParentId() && record.getRecordId() != 0) { |
| 35 | + throw new InvalidRecordsException("Invalid Records"); |
| 36 | + } |
| 37 | + treeNodes.add(new TreeNode(record.getRecordId())); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + for (int i = 0; i < orderedRecordIds.size(); i++) { |
| 43 | + TreeNode parent; |
| 44 | + for (TreeNode n: treeNodes) { |
| 45 | + if (i == n.getNodeId()) { |
| 46 | + parent = n; |
| 47 | + for (Record record : records) { |
| 48 | + if (record.getParentId() == i) { |
| 49 | + for (TreeNode node : treeNodes) { |
| 50 | + if (node.getNodeId() == 0) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + if (record.getRecordId() == node.getNodeId()) { |
| 54 | + parent.getChildren().add(node); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + break; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + if (treeNodes.size() > 0) { |
| 66 | + return treeNodes.get(0); |
| 67 | + } |
| 68 | + |
| 69 | + return null; |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments