مواظب باش: تست نشده. اما فکر کنم به خوبی منطق کار رو نشونت بده.
type
TCharData=record
Quentity:largeint;
Used:boolean;
end;
CharsData=array[char] of TCharData;
PTreeNode=^TTreeNode;
TTreeNode=record
Big,Small:PTreeNode;
Idx:integer;
SigmaQ:largeint;
end;
.
.
.
function MakeTree(ABig,ASmall:PTreeNode):PT reeNode;
(******************************)
function NewNode(ABig,ASmall:PTreeNode;AIdx:int eger;Q:largeint):PTreeNode;
var
P:PTreeNode;
begin
new(P);
with P^ do begin
Big:=ABig;
Small:=ASmall;
AIdx:=Idx;
SigmaQ:=Q;
end;
NewNode:=P;
end;
(******************************)
function FindLessQ:integer;
var
i:integer;
ch:char;
begin
i:=-1;
for ch:=#0 to #255 do
if not CharsData[ch].Used then
if i=-1 then i:=integer(ch) else
if CharsData[ch].Quentity<CharsData[ch ar(i)].Quentity then i:=integer(ch);
if i<>-1 then CharsData[char(i)].Used:=true;
FindLessQ:=i;
end;
(******************************)
procedure Swap(var a,b:PTreeNode);
var
c:PTreeNode;
begin
c:=a;
a:=b;
b:=c;
end;
(******************************)
var
i:integer;
P1,P2,P3:PTreeNode;
begin
if ABig=nil then begin
i:=FindLessQ;
P2:=NewNode(nil,nil,i,CharsData[char&# 40;i)].Quentity);
i:=FindLessQ;
P1:=NewNode(nil,nil,i,CharsData[char&# 40;i)].Quentity);
MakeTree:=MakeTree(P1,P2);
end else begin
P1:=ABig;
P2:=ASmall;
i:=FindLessQ;
if i=-1 then MakeTree:=NewNode(P1,P2,-1,P1^.Quentity+P2^.Quentity)
else begin
P3:=NewNode(nil,nil,i,CharsData[char&# 40;i)].Quentity);
if P3^.Quentity>P2^.Quentity then Swap(P2,P3);
if P2^.Quentity>P1^.Quentity then Swap(P2,P1);
MakeTree:=MakeTree(NewNode(P1,P2,-1,P1^.Quentity+P2^.Quentity),P3);
end;
end;
end;
.
.
.
.
//main prog
var
TreeRoot:PTreeNode;
.
.
begin
{initialization CharsData[aaa] with
Used:=Tree and Quentity:=frequence of using aaa character in file}
.
.
.
TreeRoot:=MakeTree(nil,nil);
.
.
.
end.