delphi递归处理树型结构

类别:Delphi 点击:0 评论:0 推荐:

type
  orgVO=record
   PK_DEPART:string;
   DEPCODE:string;
   DEPNAME:string;
   DEPTDESC:string;
   DEPPHONE:string;
   DEPADDR:string;
   PARENTID:string;
   LEVEL:integer;
end;

递归函数:
procedure Tdlg_org.dg(vos: array of zzorgVO;tnode:TTreeNode;str:string;sum:integer);
var
i:integer;
s:string;
snode:TTreeNode;
begin
  for i:= 0 to sum-1 do
  begin
    if CompareStr(trim(vos[i].PARENTID),trim(vos[i].DEPCODE))=0 then begin
      showmessage('请检查上下级编码是否一致,否则会造成死循环');
      exit;
      self.Close;
    end;
    if (vos[i].PARENTID<>'') and (CompareStr(trim(vos[i].PARENTID),trim(str))=0) then begin
      s:=vos[i].DEPCODE;
      snode:=Treeview1.items.addchild(tnode,vos[i].DEPNAME);
      dg(vos,snode,s,sum);
    end;
  end;
end;

调用递归的方法:
procedure Tdlg_org.frushTree;
var
mysql:string;
tt:TDataSource;
j:integer;
vos:array of zzorgVO;
vo:zzorgVO;
RootNode:TTreeNode;
begin
  mysql:='select PK_DEPART,DEPCODE,DEPNAME,DEPTDESC,DEPPHONE,DEPADDR,PARENTID,LEVEL1 from BD_DEPART';
  tt:=SQLzzorgDMO.Create.queryAll(mysql);
  //组成全部数据的VO
  j:=1;
  setlength(vos,tt.DataSet.RecordCount);
  while not tt.DataSet.Eof do begin
  vo.PK_DEPART:=tt.DataSet.Fields.Fields[0].AsString;
  vo.DEPCODE:=tt.DataSet.Fields.Fields[1].AsString;
  vo.DEPNAME:=tt.DataSet.Fields.Fields[2].AsString;
  vo.DEPTDESC:=tt.DataSet.Fields.Fields[3].AsString;
  vo.DEPPHONE:=tt.DataSet.Fields.Fields[4].AsString;
  vo.DEPADDR:=tt.DataSet.Fields.Fields[5].AsString;
  vo.PARENTID:=tt.DataSet.Fields.Fields[6].AsString;
  vo.LEVEL:=strtoint(tt.DataSet.Fields.Fields[7].AsString);
  vos[j-1]:=vo;
  inc(j);
  tt.DataSet.Next;
  end;
  //写入数组
  TreeView1.Items.Clear;
  for j:=0 to high(vos) do begin
    if trim(vos[j].PARENTID)='' then begin
      RootNode:=TreeView1.Items.Add(nil,vos[j].DEPNAME);
//调用递归
      dg(vos,RootNode,vos[j].DEPCODE,tt.DataSet.RecordCount);
    end;
  end;
end;

本文地址:http://com.8s8s.com/it/it4736.htm