It took me a while to work this one out, so to save anyone else the trouble here is some pseudo code showing how I went about it.
Begin your tree by setting the least common ancestor of the node list as the root node, then 'walk the tree' using the subroutine walk: walk(parent, parent, 0) :
sub walk (parent, ancestor, distance from ancestor to parent) {
For each (child of parent with nodes) {
Case (Count(children) of parent with nodes) {
0: Return
1: Case(Count(grandchildren of child with nodes)) {
0: add_child()
1: walk(child, ancestor, distance())
>1: add_child()
walk(child, child, 0)
}
>1: Case(Count(grandchildren of child with nodes)) {
0: add_child()
1: walk(child, ancestor, distance())
>1: add_child()
walk(child, child, 0)
}
}
}
return
}
Where, 'with nodes' is true where the node or any descendant nodes are in the list.
add_child(ancestor) adds the child as a descendant of the ancestor with distance from the ancestor to the child.
distance() sums the distance from parent to child to the combined distance from the ancestor to the parent calculated.
No comments:
Post a Comment