D
dfwzwhh
Unregistered / Unconfirmed
GUEST, unregistred user!
树的快速创建算法,只需读一次数据库.unit U_CreateTree;interfaceuses Classes, ComCtrls, ADODB, SysUtils;type PPNodedata=^TNodeData; TNodeData = record ID:integer;//节点编号 PID:Integer;//父节点编号 Name:string;//节点名称 childPNodedata;//孩子节点 bratherPNodedata;//兄弟节点 end; PNodeData = PPNodeData; TTreeFill1 = class(TThread) TV: TTreeView; RootID:Integer; ptrPNodeData; rootPNodeData;//根节点 PointNodePNodeData; 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;implementationuses 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:= PointNode; next; end; end; free; end;//------创建树----------for i:=0 to count-1 do begin for j:=0 to count-1 do if s^.PID=s[j]^.ID then begin if s[j]^.child=nil then s[j]^.child:=s else begin ptr:= s[j]^.child; while (ptr.brather<>nil) do ptr:=ptr^.brather; ptr.brather:=s; end; end; end; for i:=0 to count-1 do if s^.ID=RootID then begin root:=s; //根节点 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;PNNodeData);var nNode: TTreeNode; PNode,q: PNodeData;beginPNode:=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.