花了四节课的时间写出的平衡二叉树。
program balance; type link=^node; node=record data,b:longint; lch,rch,parent:link; end; var root:link; x,n,i:longint; procedure LL_rolation(var p:link); var q:link; begin q:=p^.lch; p^.lch:=q^.rch; q^.rch:=p; p:=q; p^.b:=0; p^.rch^.b:=0; end; procedure RR_rolation(var p:link); var q:link; begin q:=p^.rch; p^.rch:=q^.lch; q^.lch:=p; p:=q; p^.b:=0; p^.lch^.b:=0; end; procedure LR_rolation(var p:link); var q:link; x:longint; begin x:=p^.lch^.rch^.b; q:=p^.lch; RR_rolation(q); p^.lch:=q; LL_rolation(p); p^.b:=0; if x=1 then begin p^.lch^.b:=-1;p^.rch^.b:=0; end else begin p^.lch^.b:=0;p^.rch^.b:=-1; end; end; procedure RL_rolation(var p:link); var q:link; x:longint; begin x:=p^.rch^.lch^.b; q:=p^.rch; LL_rolation(q); p^.rch:=q; RR_rolation(p); p^.b:=0; if x=1 then begin p^.lch^.b:=-1;p^.rch^.b:=0; end else begin p^.lch^.b:=0;p^.rch^.b:=-1; end; end; procedure insert(var root:link; x:longint); var p,q,r,t,f,k:link; d:longint; begin new(p); p^.data:=x; p^.lch:=nil; p^.rch:=nil; p^.b:=0; q:=root; t:=nil; r:=root; while q<>nil do begin if q^.b<>0 then begin r:=q;f:=t; end; if x<q^.data then if q^.lch=nil then begin q^.lch:=p;break; end else begin t:=q;q:=q^.lch; end else if q^.rch=nil then begin q^.rch:=p;break; end else begin t:=q;q:=q^.rch; end; end; q:=r; if x<q^.data then begin d:=-1;q:=q^.lch; end else begin d:=1;q:=q^.rch; end; while q<>p do begin if x<q^.data then begin dec(q^.b); q:=q^.lch; end else begin inc(q^.b); q:=q^.rch; end; end; if r^.b=0 then r^.b:=d else if r^.b+d=0 then r^.b:=0 else begin k:=r; if d=-1 then case r^.lch^.b of -1:LL_rolation(k); 1:LR_rolation(k); end else if d=1 then case r^.rch^.b of -1:RL_rolation(k); 1:RR_rolation(k); end; if f=nil then root:=k else if f^.lch=r then f^.lch:=k else if f^.rch=r then f^.rch:=k; end; end; procedure print(p:link); begin if p^.lch<>nil then print(p^.lch); write(p^.data,’ ‘); if p^.rch<>nil then print(p^.rch); end; begin while not eof do begin new(root); read(x); root^.data:=x; root^.lch:=nil; root^.rch:=nil; root^.b:=0; while not eoln do begin read(x); insert(root,x); end; readln; print(root); writeln; end; end.