我使用数组编写了一个非常简单的树类。此类需要表示链接在一起的数据,但它们可以具有不同数量的连接(即,一条路径可能只有 3 个节点,而另一条路径可能有 10 个节点)。话虽如此,我需要找出一种可能的解决方案来使用具有多个叶索引的此类执行 LCA。这是我到目前为止写的代码:
public class ArrayTree {
/**
* Tree structure
*/
private int[] t;
/**
* The size of this database
*/
private int N;
/**
* Creates an array tree with the given size
*
* @param n
* the size of the array tree
*/
public ArrayTree(int n) {
N = n;
t = new int[N];
}
/**
* add a new node
*/
public void addNode(int id, int parent) {
validate(parent);
t[id] = parent;
}
/**
* Given an id this method will return an iterable object
* orderd from root to leaf
*/
public Iterable<Integer> getEntries(int id) {
validate(id);
List<Integer> entries = new ArrayList<Integer>();
while (id > 1) {
entries.add(id);
id = t[id];
if (id == 0) {
return null;
}
}
// Reorder entries from root to leaf
Collections.reverse(entries);
return entries;
}
/**
* Private method for validating indexes
*
* @param index
* the index
* @throws IndexOutOfBoundsException
* if index > N or index < 0
*/
private void validate(int index) {
if (index >= N) {
String error = String.format("Index: %d - Size: %d", index, N);
throw new IndexOutOfBoundsException(error);
} else if (index < 0) {
String error = "negative index";
throw new IndexOutOfBoundsException(error);
}
}
}
在此先感谢,干杯,
乔瓦尼