自己建了一个二叉树,建树的代码和树操作单元文件如下,在建树过程中,树操作单元文件initialization部分如果没有new(root),运行建树代码,程序就会发生错误,需要在树创建或initialization部分加上此语句,但是用作周转的变量Temp就不用new也不会引起程序运行错误,请教什么情况下new必须有,什么情况不用,顺便问dispose什么情况必须有,什么情况不用
注意函数中的SOut是用来监视函数运行的,方便调试,看代码的时候完全可以不看//建树的代码
  BinaryTreeCreate(1);
  BinaryTreeInsert(Root,2,3);
  Temp:=Root.Left;
  BinaryTreeInsert(Temp,'Left',4);
  BinaryTreeInsert(Temp,'Right',5);
  Temp:=Temp.Right;
  BinaryTreeInsert(Temp,'Left',7);
  Temp:=Temp.Left;
  BinaryTreeInsert(Temp,'Right',8);
  Temp:=Root.Right;
  BinaryTreeInsert(Temp,'Right',6);
  PriorBinaryTreeTravel();
  Form1.Caption:=Sout;
//建树的代码unit UBinaryTree;//树操作单元文件interface
uses
  SysUtils;type
  PN=^Node;  Node=record
    Data:integer;
    Left:PN;
    Right:PN;
  end;  LR=String;//仅有左孩子或右孩子插入时当标志使用var
  SOut:string;//用于显示函数运行情况
  Root:PN;//根节点
  Temp:PN;//临时使用的节点Procedure BinaryTreeCreate(Input:integer);//创建二叉树,参数是根节点记录的数据
Procedure BinaryTreeInsert
 (Parent:PN; DL,DR:integer);overload;//左右孩子都需要加入
Procedure BinaryTreeInsert
  (Parent:PN; CLR:LR; D:integer);overload;
  //仅插入一个孩子,CLR决定是左孩子还是右孩子implementationProcedure BinaryTreeCreate(Input:integer);//创建二叉树,参数是根节点记录的数据
begin
  //new(Root);
  Root.Data:=Input;
  Root.Left:=nil;
  Root.Right:=nil;
end;Procedure BinaryTreeInsert
  (Parent:PN; DL,DR:integer);overload;//左右孩子都需要加入
var
  LChild,RChild:PN;begin
  new(LChild);
  new(RChild);
  LChild.Data:=DL;
  RChild.Data:=DR;
  Parent.Left:=LChild;
  Parent.Right:=RChild;  //SOut:=SOut+IntToStr(Parent.Data)+' '+IntToStr(Parent.Left.Data)
  //       +' '+IntToStr(Parent.right.Data)+',';
end;Procedure BinaryTreeInsert
  (Parent:PN; CLR:LR; D:integer);overload;
  //仅插入一个孩子,CLR决定是左孩子还是右孩子
var
  ChildLR:PN;begin
  new(ChildLR);
  ChildLR.Data:=D;
  ChildLR.Left:=nil;
  ChildLR.Right:=nil;  if CLR='Left' then
  begin
    Parent.Left:=ChildLR;
    //SOut:=SOut+IntToStr(Parent.Data)+' '+IntToStr(Parent.Left.Data)+',';
  end;
  
  if CLR='Right' then
  begin
    Parent.Right:=ChildLR;
    //SOut:=SOut+IntToStr(Parent.Data)+' '+IntToStr(Parent.Right.Data)+',';
  end;
end;initialization
  SOut:='';
  new(Root);
  //new(Temp); //为什么不要本语句也可以执行?
end.

解决方案 »

  1.   

    Temp:=Root.Left; 
    -------------
    只做临时交货,Temp指向Root.Left地址,
    你创建了的话,如果没有释放,反而会内存泄露。
      

  2.   

    为什么会内存泄露,而且root不new就不能正常运行啊
      

  3.   


    New PN是指向一個結構的指針,當使用時就需要分配內存。DisPose 是你 New 過就要釋放,釋放時間由你自己來定.最好將指針用 TLIST 管理起來。因為你的樹比較難處理釋放
      

  4.   

    就没有人提供为什么Temp不需要new,而root必须new的问题吗
      

  5.   

    就没有人提供为什么Temp不需要new,而root必须new的问题吗