Acasa Tehnologie Arbori: citire, suma nodurilor, afisare

Arbori: citire, suma nodurilor, afisare

by Dragos Schiopu

programare

>Suma noduri, suma noduri pare,citire din fisier,determinare numar niveluri in arbore, afisare noduri de pe un nivel cerut.

type arbore=^ref;
     ref=record
               inf:integer;
               st,dr:arbore;
     end;
var r:arbore;
    f:text;
    nivel:integer;
procedure creare(var p:arbore);
var val:integer;
begin
     read(f,val);
     if val=0 then p:=nil
            else
                begin
                     new(p);
                     p^.inf:=val;
                     creare(p^.st);
                     creare(p^.dr);
                end;
end;
procedure preordine(p:arbore);
begin
     if p<>nil then
                   begin
                        write(p^.inf:4);
                        preordine(p^.st);
                        preordine(p^.dr);
                   end;
end;
function suma(p:arbore):integer;
begin
     if p=nil then suma:=0
              else suma:=p^.inf+suma(p^.st)+suma(p^.dr);
end;
function suma_p(p:arbore):integer;
begin
     if p=nil then suma_p:=0
              else
                  if p^.inf mod 2=0 then suma_p:=p^.inf+suma_p(p^.st)+suma_p(p^.dr)
                                    else suma_p:=suma_p(p^.st)+suma_p(p^.dr)

end;
function inaltime(p:arbore):integer;
var inaltime_s,inaltime_d:integer;
begin
     if p=nil then inaltime:=0
              else
                  begin
                       inaltime_s:=inaltime(p^.st);
                       inaltime_d:=inaltime(p^.dr);
                       if inaltime_s<=inaltime_d then inaltime:=inaltime_d+1
                                                 else inaltime:=inaltime_s+1;
                  end;
end;
procedure nod_nivel(p:arbore;k:integer;var nivel:integer);
begin
     if p<>nil then
                   begin
                        if k=nivel then write(p^.inf:4);
                        nod_nivel(p^.st,k+1,nivel);
                        nod_nivel(p^.dr,k+1,nivel);
                   end;
end;
BEGIN
     r:=nil;
     assign(f,'arbore.txt');
     reset(f);
     creare(r);
     close(f);
     writeln('parcurgere in preordine-RSD');
     preordine(r);
     writeln;
     writeln('suma nodurilor=', suma(r));
     writeln('suma nodurilor pare=',suma_p(r));
     writeln('arborele are ',inaltime(r),' nivele');
     write('nivelul=');readln(nivel);
     nod_nivel(r,1,nivel);
     readln;
END.
{PascalZone.uv.ro}

s-ar putea sa-ti placa