【问题标题】:How to convert a tree recursive function ( or algorithm ) to a loop one?如何将树递归函数(或算法)转换为循环函数?
【发布时间】:2010-07-27 10:37:12
【问题描述】:

我在 pascal(或 delphi)中编写了一个递归树函数,但是当我运行它时出现“内存不足”消息。 我需要将此代码中的计算递归函数转换为非递归函数,你能告诉我怎么做吗:

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.

【问题讨论】:

  • 请编辑您的问题。请阅读页面右侧的代码格式说明。

标签: algorithm delphi recursion tree pascal


【解决方案1】:

递归函数使用堆栈来保持递归的状态。

转换为循环时,您必须实际创建一个显式堆栈。您必须在循环内从堆栈中推送和弹出元素。

【讨论】:

  • 小记:在这种情况下(每次迭代有多个递归调用)这是真的,但简单的自动递归通常可以在没有堆栈或其他依赖于 N 的状态的情况下重写。
猜你喜欢
  • 2013-05-31
  • 2020-11-01
  • 2018-07-13
  • 2012-02-03
  • 2019-05-30
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
相关资源
最近更新 更多