Implement tree construction and encode, decode