将递归算法精确模拟为迭代

时间:2017-06-15 18:48:06

标签: algorithm recursion iteration

我被要求用迭代算法精确模拟递归算法。完全意味着我必须模拟真正的pc在执行期间所做的堆栈记录。 假设我有一个二进制搜索树,其中只包含一个键和两个左右的参考,我想这样做:

CountOddRec(T)
  ret = 0
  if T != NIL then
      if T->key % 2 = 1 then
          ret = T->key
      rsx = CountOddRec(T->sx);
      rdx = CountOddRec(T->dx);
      ret = ret + rsx + rdx;
  return ret

基本上我的想法是使用迭代二叉树访问的一般方案来做到这一点:

VisitIter(T)
  last = NIL 
  curr = T
  stk = NULL
  while (curr != NIL || stk != NIL) do
      if curr != NIL then
          //Pre-order visit
          stk = push(stk, curr)
          next = curr->sx 
      else
          curr = Top(stk)

          if (last != curr-> dx) then
              //In-order visit

          if (last != curr-> dx  && curr->dx != NULL) then
              next  = curr->dx
          else
              //Post-order visit
              stk = pop(stk)
              next = NIL
      last = curr
      curr = next

现在我知道这个应该在预购区块中:

      if T->key % 2 = 1 then
          ret = T->key

rsx =分配应该是有序的,rdx =分配和最后一个分区应该在后期。 现在我陷入困境,我问是否有人可以帮助我理解算法是如何完成的。

修改 我已经改变了有序访问,因为它不正确,那么这是我应该工作的第一次尝试:

CountOddIter(T)
  last = NIL 
  curr = T

  stk = NULL //stack
  Sret = NULL //stack
  Srsx = NULL //stack

  ret = 0

  while (curr != NIL || stk != NIL) do
      ret = 0
      if curr != NIL then
          //Pre-order block
          if (curr->key % 2 == 1) then
              ret = curr->key

          Sret = push(Sret, ret)

          stk = push(stk, curr)
          next = curr->sx 
      else
          curr = Top(stk)

          if (last != curr-> dx) then
              //In-order block
              Srsx = push(Srsx, pop(Sret))

          if (last != curr-> dx  && curr->dx != NULL) then
              next  = curr->dx
          else
              //Post-order block
              rdx = pop(Sret)
              rsx = pop(Srsx)
              r = pop(Sret)

              ret = rdx + rsx + r

              Sret = push(Sret, ret)

              stk = pop(stk)
              next = NIL
      last = curr
      curr = next

如果我假设空堆栈上的pop返回0,则此方法有效。 还有其他建议吗?改进?

0 个答案:

没有答案