using template function for BuildTree()