Update algorithm to build tree