List to tree function