问题
In my code, Java TreeSet iteration is the dominant time factor. In looking at the system I believe that it is O(n) complexity. Can anyone verify this?
I am thinking that by providing links backward from child node to parent node I could improve the performance.
回答1:
TreeSet
iteration is of course O(n), as can be expect from any sensible tree-walking algorithm.
I am thinking that by providing links backward from child node to parent node I could improve the performance.
TreeMap
(which TreeSet
is based on) already has such parent references. This is the method it all boils down to:
private Entry<K,V> successor(Entry<K,V> t) {
if (t == null)
return null;
else if (t.right != null) {
Entry<K,V> p = t.right;
while (p.left != null)
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
回答2:
Have you considered taking a copy of the TreeSet when you alter it? If the dominate time is spent in TreeSet iteration (rather than modifying it) then copying the TreeSet to an array or ArrayList (only when altered) and only iterating over this array/ArrayList could almost elminate the cost of TreeSet iteration.
来源:https://stackoverflow.com/questions/2759256/what-is-the-time-complexity-of-treeset-iteration