以下代码在Windows2000+D5下运行通过!
强调一点,算法和语言没什么联系,各种语言都有各自的优点,希望楼主的朋友不要门缝里看人!
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
TV1: TTreeView;
TV2: TTreeView;
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
private
function ChkTreeItem(iLevel: integer; sTxt: string; TV: TTreeView): boolean;
procedure AddTreeItem(PNode: TTreeNode; sTxt: string; TV: TTreeView);
function CheckSite(const Str, Ch: string;
var Mystring: TStrings): boolean;
function GetNode(iLevel: integer; PTxt: string; TV: TTreeView): TTreeNode;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1 : TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
CNode, aNode : TTreeNode;
i : integer;
sNTxt, sPTxt, sStr: string;
slStr, slTmp : TStrings;
begin
slStr := TStringList.Create;
slTmp := TStringList.Create;
for i := 0 to TV2.Items.Count - 1 do
begin
CNode := TV2.Items;
//检测在TV1中是否有TV2中的节点?
if not ChkTreeItem(CNode.Level, CNode.Text, TV1) then
begin
sNTxt := CNode.Text;
Label2.Caption := Label2.Caption + ',' + sNTxt;
if CNode.Parent <> nil then
sPTxt := CNode.Parent.Text
else
sPTxt := '';
//保存TV1中没有节点信息(txt,级别,父节点txt)
slStr.Add(sNTxt + ',' + Inttostr(CNode.Level) + ',' + sPTxt);
end;
end;
for i := 0 to slStr.Count - 1 do
begin
sStr := slStr;
CheckSite(sStr, ',', slTmp);
aNode := GetNode(StrToInt(slTmp[1]), slTmp[2], TV1); //得到TV1中相关节点的父节点
AddTreeItem(aNode, slTmp[0], TV1); //创建节点
end;
slStr.Free;
end;
function TForm1.GetNode(iLevel: integer; PTxt: string; TV: TTreeView):
TTreeNode;
var
i : integer;
CNode : TTreeNode;
sPTxt : string;
begin
Result := nil;
if iLevel > 0 then iLevel := iLevel - 1; //父亲节点的级数
for i := 0 to TV.Items.Count - 1 do
begin
CNode := TV.Items;
sPTxt := CNode.Text;
if (sPtxt = PTxt) and (CNode.Level = iLevel) then //级数相等且标签相等则返回当前节点
begin
Result := CNode;
Break;
end;
end;
end;
procedure TForm1.AddTreeItem(PNode: TTreeNode; sTxt: string; TV: TTreeView);
begin
TV.Items.AddChild(PNode, sTxt); //创建节点
end;
function TForm1.CheckSite(const Str, Ch: string; var Mystring: TStrings)
: boolean;
{字符串Str以Ch分隔成几段小字符串,该函数是将这些小字符串提取出来并保存在MyString中}
{截取字符串两边的空格}
var
sit, n : integer;
S : string;
begin
Result := True;
MyString.Clear;
S := Str;
n := Length(Ch);
while True do
begin
if Pos(Ch, S) = 0 then
begin
MyString.Add(S);
Break;
end;
sit := Pos(Ch, S);
MyString.Add(Copy(S, 1, sit - 1));
S := Trim(Copy(S, sit + n, Length(S)));
end;
if MyString.Count < 2 then Result := False;
end;
function TForm1.ChkTreeItem(iLevel: integer; sTxt: string; TV: TTreeView):
boolean;
var
i : integer;
CNode : TTreeNode;
begin
Result := False;
for i := 0 to TV.Items.Count - 1 do
begin
// Label1.Caption := inttostr(i) + ' ' + inttostr(TV.Items.Count);
try
TV.Items.Selected;
CNode := TV.Selected;
if (CNode.Level = iLevel) and (CNode.Text = sTxt) then
begin
Result := True;
Break;
end;
except
Result := False;
end;
end;
end;
end.