Refactored tree construction algorithm.