Domanda

So im trying to add all 'spent' data, belonging to specific client number, on a binary tree.

Type

pointer_tree = ^bTree;    
bTree = record
     nclient: integer;
     spent: integer;
     big, small: pointer_tree
end;

{adder is 0}
function add (pT: pointer_tree; client_number: integer; adder: integer): integer;
begin
     if pT <> nil then begin
        if pT^.nclient = client_number then
           adder:= pT^.spent + adder
        add(pT^.big,client_number,adder);
        add(pT^.small,client_number,adder);
     end;
     add:= adder;
end;

Function add will not return the added elements and will return a random number instead. Also is there a better way to add them all up?

È stato utile?

Soluzione

I don't like the way that you're using the variable 'adder' as both a parameter to the function and also as a temporary store for the calculated value. I think it would be better if the function were written as follows, without the 'adder' variable:

function add (pT: pointer_tree; client_number: integer): integer;
begin
 result:= 0;
 if pT <> nil then 
  begin
   if pT^.nclient = client_number then result:= pT^.spent;
   inc (result, add (pT^.big, client_number));
   inc (result, add (pT^.small, client_number));
  end;
end;

Incidentally, your code is missing a semicolon after the 'adder:= pT^.spent + adder' line.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top