views:

126

answers:

2

I have written a recursive Tree Function in pascal ( or delphi ) but i had an 'Out of Memory' message when I ran it. I need to turn the Calculate recursive function in this code to non-recursive function, can you tell me how please :

program testing(input,output);
type
  ptr = ^tr;
  tr = record
    age:byte;
    left,right:ptr;
  end; 
var
  topper:ptr;
  total,day:longint;
procedure mycreate(var t:ptr);
var temp:ptr;
begin
  new(temp);
  temp^.age:=1;
  temp^.left:=nil;
  temp^.right:=nil;
  t:=temp;
end;
procedure gooneday(var t:ptr);
begin
  if t^.age<>5 then
    begin
      if t^.age=2 then
        mycreate(t^.left)
      else if t^.age=3 then
        mycreate(t^.right);
      t^.age:=t^.age+1;
      total:=total+1;
    end;
end;

procedure calculate(var crnt:ptr);
begin
  if crnt<>nil then
    begin
      gooneday(crnt);
      calculate(crnt^.left);
      calculate(crnt^.right);
    end;
end;

begin
  total:=0;
  mycreate(topper);
  day:=0;
  while total<1000000000000 do
    begin
      total:=0;
      day:=day+1;
      calculate(topper);
    end;
  writeln(day);
  writeln(total);
end.
+4  A: 

Recursive functions use a stack to keep the state of the recursion.

When converting to a loop, you must actually create an explicit stack. You must push and pop elements off the stack within the loop.

S.Lott
Small note: in this case (with multiple recursive calls per iteration) this is true, but simple autorecursion can often be rewritten without stack or other state dependant on N.
Marco van de Voort
+2  A: 

You could traverse the tree in constant space. You could see at this disscussion.

Dmitry
Traversing in constant space with this technique involves giving each node a parent pointer. This is fine and all until you want to start copying nodes by reference (rather than deep copying). When you make a node a child of multiple trees, it can no longer have a single correct parent pointer. Before going down the parent pointer road, spend some time thinking about whether or not you can do without referencing the same node in a tree multiple times.
Joey Adams