delphi save and load Binary Tree

醉酒当歌 提交于 2019-12-11 07:45:10

问题


please , suppose i have this Binary Tree structure :

Type
    TPMyTree = ^TMyTree;
    TMyTree = Record
        ID:Integer;
        FullName:String[50];//<-------- fixed
        addrs:String[50] // <----------- fixed
        LeftT:TPMyTree;
        RightT:TPMyTree;
    end;

How could i save and load it from a Stream ?


回答1:


When working with streams, the most complex issue is dealing with variable-length data. In your case that's the FullName and the addrs, because those fields are of type String. The easiest solution is to use Delphi's stream reader and writer helper classes, TReader and TWriter, because they provide easy means of working with string. Other thant that the most obvious solution is to write the tree to the stream recursively, one node at a time.

Warning, code written in browser window:

// This will save one node to the stream, using the TWriter helper. Takes
// care of potential NIL's.
procedure SaveBinaryTreeToStreamWriter(RootNode: TPMyTree; W: TWriter);
begin
  if Assigned(RootNode) then
    begin
      W.WriteBoolean(True);
      W.WriteInteger(RootNode^.ID);
      W.WriteString(RootNode^.FullName);
      W.WriteString(RootNode^.addres);
      SaveBinaryTreeToStreamWriter(RootNode^.LeftT, W);
      SaveBinaryTreeToStreamWriter(RootNode^.RightT, W);
    end
  else
    W.WriteBoolean(False);
end;

// This will read one NODE from the stream, using the TReader helper.
// Uses the boolean "nil" marker saved by the writing routine to also
// return "nil" if needed.
function ReadBinaryTreeNodeFromReader(R: TReader):TPMyTree;
begin
  if R.ReadBoolean then
    begin
      Result := AllocMem(SizeOf(TMyTree));
      Result^.ID := R.ReadInteger;
      Result^.FullName := R.ReadString;
      Result^.addres := R.ReadString;
      Result^.LeftT := ReadBinaryTreeNodeFromReader(R);
      Result^.RightT := ReadBinaryTreeNodeFromReader(R);
    end
  else
    Result := nil;
end;

// This simply creates the TWriter and then starts the recursive process of
// writing the tree to stream.
procedure SaveBinaryTreeToStream(RootNode: TPMyTree; Stream: TStream);
var W:TWriter;
begin
  W := TWriter.Create(Stream, 128);
  try
    SaveBinaryTreeToStreamWriter(RootNode, W);
  finally W.Free;
  end;
end;    

// This simply creates the TReader and then starts the recursive process of
// reading the tree one node at a time:
function ReadFromStream(Stream:TStream):TPMyTree;
var R: TReader;
begin
  R := TReader.Create(Stream, 128);
  try
    Result := ReadBinaryTreeNodeFromReader(R);
  finally R.Free;
  end;    
end;


来源:https://stackoverflow.com/questions/8819885/delphi-save-and-load-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!