I have VirtualStringTree (VST) with nodes that have the next data structure :
Type
PMyNodeData = ^TMyNodeData;
TMyNodeData = record
Cost:UnicodeString;
end;
The Child nodes which they don't have any children has Cost value but any parent nodes has cost value equaled to 0 and am trying to write procedure to make any parent node cost value equaled to sum of all its children cost .
I have tried the next :
procedure CalculateSum(Node:PVirtualNode);
var
Data: PMyNodeData;
ChildNode: PVirtualNode;
ChildData: PMyNodeData;
CostSum: Extended;
begin
Data := VST.GetNodeData(Node);
CostSum := 0.0;
ChildNode := VST.GetFirstChild(Node);
while Assigned(ChildNode) do
begin
ChildData := VST.GetNodeData(ChildNode);
CostSum := CostSum + StrToFloat(ChildData.Cost);
CalculateSum(ChildNode);
ChildNode := VST.GetNextSibling(ChildNode);
end;
if VST.HasChildren[Node] and (StrToFloat(Data.Cost) = 0) then
Data.Cost := FloatToStr(CostSum);
end;
The use :
CalculateSum(vst.RootNode);
But I get Access violation & the sum is not correct .. any suggestions.
I have solved the issue as the next :
procedure CalculateSum(Node: PVirtualNode);
var
Data: PMyNodeData;
ChildNode: PVirtualNode;
ChildData: PMyNodeData;
CostSum: Extended;
begin
Data := VST.GetNodeData(Node);
if data<>nil then
CostSum := Data.Cost else Costsum:=0.0;
ChildNode := VST.GetFirstChild(Node);
while Assigned(ChildNode) do
begin
ChildData := VST.GetNodeData(ChildNode);
if ChildData <> nil then
begin
CalculateSum(ChildNode);
CostSum := CostSum + ChildData.Cost;
end;
ChildNode := VST.GetNextSibling(ChildNode);
end;
if (VST.HasChildren[Node]) and (Data<>nil) then
Data.Cost := CostSum;
end;