Efficient Tree Structure Hierarchy Rebuild
I'm having a tree structure like this:
1 ABC
1.1 DEF
1.1.2 GHI
1.2 JKL
1.2.1 MNO
2 PQR
2.1
... with no limits on the depth and le开发者_如何学Gongth of each level. Now what happens is that I take out some of the elements all around the tree structure and in the end I want to have a proper, restructured hierarchy numbering.
How do you usually re-sort & apply proper hierarchy numbering in the least amount of work in such a case? This is a somewhat basic use case, but I'm looking for some room for improvement.
I suppose that you are keeping both number and the text in the same value
variable.
The simplest thing you could possibly do is to:
- Separate that into two variables:
number
andtext
- Whenever you are swapping two tree nodes (i.e. during sorting) swap just
text
values and keep thenumber
values where they are. - Whenever you are adding new element as the last subelement, just use the
previousLastElement.number + 1
- Whenever you print out the elements number reversly append all its parents numbers separated by dot.
The only remaining complexity now is when you insert elements, where you would have to "push" the other elements' numbers after that one (but only on that one level), or when you remove elements, when you would have to pull them.
You could use a priority queue like a self-balancing tree.
精彩评论