树的快速创建算法,只需读一次数据库.
unit U_CreateTree;
interface
uses Classes, ComCtrls, ADODB, SysUtils;
type PPNodedata=^TNodeData; TNodeData = record ID:integer;//节点编号 PID:Integer;//父节点编号 Name:string;//节点名称 child:PPNodedata;//孩子节点 brather:PPNodedata;//兄弟节点 end; PNodeData = PPNodeData; TTreeFill1 = class(TThread) TV: TTreeView; RootID:Integer; ptr:PPNodeData; root:PPNodeData;//根节点 PointNode:PPNodeData; s:array[0..10000] of PPNodeData; constructor Create(Root_Id:integer;ATreeView: TTreeView); private procedure AddTree(Node: TTreeNode; PN: PNodeData); protected procedure Execute; override; end;
implementation
uses U_Main, DateUtils;
var count,nodeCount:Integer; //---------- constructor TTreeFill1.Create(Root_Id:integer;ATreeView:TTreeView); begin TV:= ATreeView; TV.Items.Clear; RootID:=Root_Id; inherited Create(False); end; //---------- procedure TTreeFill1.Execute; var Query: TADOQuery; i,j:Integer; Node: TTreeNode; begin FreeOnTerminate := True; TV.Items.Clear; with Query do begin Query := TADOQuery.Create(nil); Connection := frm_Main.ADOC_SQL;//需要更改 Close; SQL.Clear; SQL.Add('Select * from 部门表 order by 部门编号 '); Open; first; count:=recordcount; if count>0 then begin for i:=0 to recordcount-1 do begin new(PointNode); PointNode^.child:=nil; PointNode.brather:=nil; PointNode^.ID:=fieldbyname('部门编号').AsInteger; PointNode^.PID:=fieldbyname('父部门编号').AsInteger; PointNode^.Name:=fieldbyname('部门名称').AsString; s[i]:= PointNode; next; end; end; free; end; //------创建树---------- for i:=0 to count-1 do begin for j:=0 to count-1 do if s[i]^.PID=s[j]^.ID then begin if s[j]^.child=nil then s[j]^.child:=s[i] else begin ptr:= s[j]^.child; while (ptr.brather<>nil) do ptr:=ptr^.brather; ptr.brather:=s[i]; end; end; end; for i:=0 to count-1 do if s[i]^.ID=RootID then begin root:=s[i]; //根节点 break; end; Node:=TV.Items.AddObject(nil,Root^.Name,Root);//创建树的根节点 nodeCount:=0; Node.ImageIndex := 0; Node.SelectedIndex := 2; AddTree(Node,root); end;
procedure TTreeFill1.AddTree(Node:TTreeNode;PN:PNodeData); var nNode: TTreeNode; PNode,q: PNodeData; begin PNode:=PN; if PNode.child<>nil then begin q:=PNode.child; while (q<>nil) do begin nNode:=TV.Items.AddchildObject(Node,q^.Name,q); nodeCount:=nodeCount+1; AddTree(nNode,q); q:=q^.brather; end; end; end;
end.
作者qq:13575437 |