Make a tree from a flattened set of nodes

This is a problem posed by Jens Peterson on Stackoverflow

1. Chris Wallace's solution

First time I've used intersect I think

2. Chris Wallace's solution with intersect replaced by precedence operator.

intersect replaced by node precedence al la Jens solution

3. Jens Erat's solution

after modifications