Create a empty hashtable H which stores degree of nodes, kind of dynamic programming.
Say your Arraylist is A, the result Arraylist will be B, the sub-result will be B1, B2,...Bn
1. Pick up any element a1 from A, remove it from A and put it into B1.
scan A get the a1's parent(remove it and put it to B1) until it reaches the root a1Root,
at same time, store every nodes with it's degree in this path into H.
You get a partial tree B1, any nodes in B1 should be removed from A
2. repeat step 1 to get B2, scan B1 to see if B2's parent is in B1, if it is, combine B1 and B2.
3. repeat step 1 and step2 until A is empty.
4. sort B1,B2,...Bn based on the degree of each nodes(COMPARATOR, get degree from H)
5. group B1,B2,...Bn to B
remember:
orphaned node is a tree as well, if you want the orphan to be the end of the list, check the size when grouping.
Say your Arraylist is A, the result Arraylist will be B, the sub-result will be B1, B2,...Bn
1. Pick up any element a1 from A, remove it from A and put it into B1.
scan A get the a1's parent(remove it and put it to B1) until it reaches the root a1Root,
at same time, store every nodes with it's degree in this path into H.
You get a partial tree B1, any nodes in B1 should be removed from A
2. repeat step 1 to get B2, scan B1 to see if B2's parent is in B1, if it is, combine B1 and B2.
3. repeat step 1 and step2 until A is empty.
4. sort B1,B2,...Bn based on the degree of each nodes(COMPARATOR, get degree from H)
5. group B1,B2,...Bn to B
remember:
orphaned node is a tree as well, if you want the orphan to be the end of the list, check the size when grouping.