program arbori_binari;
type pnod=^nod;
nod=record
info:integer;
st,dr:pnod
end;
procedure genarb(var p:pnod; vl:integer);
begin
if p=nil then
begin
new(p);
p^.info:=vl;
p^.st:=nil;
p^.dr:=nil;
exit
end;
if p^.info=vl then exit;
if p^.info<vl then genarb(p^.dr,vl)
else genarb(p^.st,vl);
end;
procedure inordine(p:pnod);
begin
if p<>nil then
begin
inordine(p^.st);
write(p^.info,' ');
inordine(p^.dr);
end;
end;
procedure postordine(p:pnod);
begin
if p<>nil then
begin
inordine(p^.st);
inordine(p^.dr);
write(p^.info);
end;
end;
function adancime(p:pnod):integer;
var a1,a2:integer;
begin
if p=nil then adancime:=-1;
if p<>nil then
begin
a1:=adancime(p^.st);
a2:=adancime(p^.dr);
if a1>a2 then adancime:=a1+1
else adancime:=a2+1;
end;
end;
function echilibrat(p:pnod):boolean;
var e1,e2,e3:boolean;
begin
if p=nil then echilibrat:=true;
if p<>nil then
begin
if abs(adancime(p^.st)-adancime(p^.dr)) <=1 then e1:=true;
e2:=echilibrat(p^.st);
e3:=echilibrat(p^.dr);
if (e1=true) and (e2=true) and (e3=true) then echilibrat:=true
else echilibrat:=false;
end;
end;
function frunza(p:pnod):integer;
var f1,f2:integer;
begin
if p=nil then frunza:=1;
if p<>nil then
begin
f1:=frunza(p^.st);
f2:=frunza(p^.dr);
if (p^.st=nil) and (p^.dr=nil) then frunza:=f1+f2+1
end;
end;
var n,i,x:integer;
var p:pnod;
begin
write('dati n-ul');
readln(n);
write('dati valorile');
for i:=1 to n do
begin read(x);readln;
genarb(p,x); end;
writeln('afisarea arborelui...');
inordine(p);
writeln('arborele este...',echilibrat(p));
writeln('arborele are atatea frunze:',frunza(p));
readln;
end.