Acasa Tehnologie Arbori de cautare

Arbori de cautare

by Dragos Schiopu

>

{creare arbore de cautare si stergere valoare data }
type arb=^ref;
ref=record
inf:integer;
st,dr:arb;
end;
var rad,aux:arb;
n:integer;
r:char;
procedure creare(var rad:arb;val:integer);
begin
if rad=nil then
begin
new(rad);
rad^.inf:=val;
rad^.st:=nil;
rad^.dr:=nil;
end
else if val<=rad^.inf then creare(rad^.st,val)
else creare(rad^.dr,val);
end;
procedure srd(rad:arb);
begin
if rad<>nil then
begin

srd(rad^.st);
write(rad^.inf:5);
srd(rad^.dr);
end;
end;
{ procedura de stergere a unui nod care are subarbori sting si drept }
procedure sterg1(var p,q:arb);
begin
if q^.dr<>nil then sterg1(p,q^.dr)
else
begin
p^.inf:=q^.inf;
aux:=q;
q:=q^.st;
dispose(aux);
end;
end;
procedure stergere(var p:arb;n:integer);
var q:arb;
begin
if p=nil then writeln('valoarea ',n,' nu exista')
else
if n=p^.inf then
begin
{ daca este virf terminal }
if (p^.st=nil) and(p^.dr=nil) then
begin
dispose(p);
p:=nil;
end
else
{ daca nu are subarbore sting }
if p^.st=nil then
begin
q:=p^.dr;
dispose(p);
p:=q;
end
else begin
{ daca nu are subarbore drept }
if p^.dr=nil then
begin
q:=p^.st;
dispose(p);
p:=q;
end
else
{ are subarbore drept }
sterg1(p,p^.st);
end
end
else if p^.inf<n then stergere(p^.dr,n)
else stergere(p^.st,n);
end;
BEGIN
writeln(' crearea unui arbore de cautare ');
rad:=nil;
repeat
write('valoarea=');
readln(n);
if n<>0 then creare(rad,n);
until n=0;
writeln('parcurgerea in stinga radacina dreapta :');
srd(rad);
writeln;
write('stergi?');readln(r);
repeat
write('valoarea pe care o stergi :');
readln(n);
stergere(rad,n);
writeln('parcurgerea in stinga radacina dreapta :');
srd(rad);
writeln;
writeln('stergi? (d/n)');readln(r);
until (r='n') or(r='N');
readln;
END.
{PascalZone.uv.ro}

s-ar putea sa-ti placa