%macro tree(_inds=);
proc sql noprint;
select distinct tree into :varlist separated by ' '
from &_inds;
quit;
%let i=1;
%let var=%scan(&varlist,&i,%str( ));
%do %while(&var ne );
data tmp pool;
set &_inds;
where tree="&var";
by tree;
n+1;
if last.tree then call symput("n",strip(put(n,best.)));
rename source_account=_1 target_account=_2;
if _n_=1 then output tmp;
else output pool;
drop n id;
run;
%do j=1 %to %eval(&n-1);
data tmp;
merge tmp(in=a) pool(rename=(_2=_%eval(&j+2) _1=_%eval(&j+1)));
by tree _%eval(&j+1);
if a;
run;
%end;
data &var;
set tmp;
run;
%let i=%eval(&i+1);
%let var=%scan(&varlist,&i,%str( ));
%end;
%mend;
%tree(_inds=test);