如何将树递归函数(或算法)转换为循环函数?

发布于 2024-09-11 17:58:12 字数 1102 浏览 2 评论 0原文

我在 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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ヤ经典坏疍 2024-09-18 17:58:12

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文