-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPruferCode.java
46 lines (37 loc) · 1.34 KB
/
PruferCode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.Collections;
import java.util.ListIterator;
public class PruferCode {
private final ArrayList<Integer> code;
private final TreeNode treeRoot;
public PruferCode(ArrayList<Integer> code) {
this.code = code;
this.treeRoot = buildTree();
}
public ArrayList<Integer> getCode() {
return code;
}
public TreeNode getTreeRoot() {
return treeRoot;
}
//
private TreeNode buildTree() {
int n = code.size() + 1;
ListIterator<Integer> codeIterator = code.listIterator();
ArrayList<Boolean> visited = new ArrayList<>(Collections.nCopies(n + 1, false));
int label = codeIterator.next();
TreeNode root = new TreeNode(label, null, null);
TreeNode node = root;
visited.set(label, true);
while (codeIterator.hasNext()) {
int next = codeIterator.next();
label = visited.get(next) ? visited.indexOf(false) : next;
TreeNode child = new TreeNode(label, root, node);
node.addChild(child);
node = label == next ? child : root.findDescendant(next);
visited.set(label, true);
}
node.addChild(new TreeNode(visited.indexOf(false), root, node));
return root;
}
}