delphi保存并加载二叉树 [英] delphi save and load Binary Tree

查看:238
本文介绍了delphi保存并加载二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请假定我具有此二叉树结构:

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;

我如何从Stream保存并加载它?

How could i save and load it from a Stream ?

推荐答案

使用流时,最复杂的问题是处理可变长度数据.在您的情况下,这是FullNameaddrs,因为这些字段的类型是String.最简单的解决方案是使用Delphi的流读取器和写入器帮助器类TReaderTWriter,因为它们提供了使用字符串的简便方法.除了最明显的解决方案,就是将树递归地写入流中,一次一个节点.

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;

这篇关于delphi保存并加载二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆