Tree Generating Algorithm