Begin treealgorithm function