build, flatten and walk trees