consolidate for loops when building tree
rename level field to depth to reflect actual behavior