【问题标题】:Turn conditional recursion algorithm to an iterative one将条件递归算法转换为迭代算法
【发布时间】:2014-01-05 18:42:18
【问题描述】:

最近我写了一个基于递归的算法来水平打印二叉树。 一般来说,将基于递归的算法转换为基于迭代的算法没有任何问题,但我就是不知道如何做到这一点。

假设我们是一个向量

std::vector<int> tree = {10,9,8,7,6,5,4};

代表以下树:

     10
    / \
   9   8
  /\   /\
 7 6   5 4

我的算法通过以下途径起作用:

index ->  left -> left      Or in our case 10 -> 9 -> 7
               -> right                            -> 6
      -> right -> left                        -> 8 -> 5
               -> right                            -> 4

等并根据树的大小进行扩展。我无法想到的是,当我有条件地使用递归时,如何将代码转换为 while 循环。我不太擅长解释,所以这里是代码。

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unistd.h>

/* The Padding function handles the spacing and the vertical lines whenever we print a  *
 * right child. This depends on the previous parent-child hierarchy of the child        *
 * Printer handles the work of printing the elements and uses a depth-first-search      *
 * algorithm as it's core. Left children are printed horizontally while the right ones  *   
 * are printed vertically. Print_tree is a wrapper. It also finds the max-length value  *
 * which will be used for formatting so that the formatting won't get messed up because *
 * of the different number of digits.                                                   */           

std::string do_padding (unsigned index, unsigned mlength){
  std::string padding;
  while(int((index-1)/2) != 0){
    padding = (int((index-1)/2) % 2 == 0) ?
    std::string(mlength+4,' ') + " "  + padding :
    std::string(mlength+3,' ') + "| " + padding ;
    index = int((index-1)/2);
  }
  return padding;
}

template <class T>
void printer (std::vector<T> const & tree, unsigned index, unsigned mlength){
  auto last = tree.size() - 1 ;
  auto  left = 2 * index + 1 ;
  auto  right = 2 * index + 2 ;
  std::cout << " " << tree[index] << " " ;
  if (left <= last){
    auto llength = std::to_string(tree[left]).size();
    std::cout << "---" << std::string(mlength - llength,'-');
    printer(tree,left,mlength);
    if (right <= last) {
      auto rlength = std::to_string(tree[right]).size();
      std::cout << std::endl<< do_padding(right,mlength) << std::string(mlength+ 3,' ') << "| " ;
      std::cout << std::endl << do_padding(right,mlength) << std::string(mlength+ 3,' ') << "└─" <<
      std::string(mlength - rlength,'-');
      printer(tree,right,mlength);
    }
  }
}

template <class T>
void print_tree (std::vector<T> & tree){
  unsigned mlength = 0;
  for (T & element : tree){
    auto length = std::to_string(element).size();
    if (length > mlength) {
      mlength = length;
    }
  }
  std::cout <<  std::fixed << std::string(mlength- std::to_string(tree[0]).size(),' ') ;
  printer(tree,0,mlength);
}

int main() {
  std::vector<int> test;
  for (auto i =0; i != 200; ++i) {
    test.push_back(rand() % 12200);
  }
  std::make_heap(test.begin(),test.end());
  std::cout << std::endl << "Press ENTER to show heap tree.." << std::endl;
  std::cin.ignore();
  print_tree(test);
  std::cout << std::endl;
}

这可能不值得重写,但我想知道如何处理这样的递归,以防我将来必须做类似的事情。

【问题讨论】:

    标签: c++ algorithm recursion tree


    【解决方案1】:

    我记得,您发布了Print heap array in tree format 问题。所以,对我来说(没有阅读代码),你的树遍历核心算法是DFS

    要使这个递归算法迭代,您可以做的是使用堆栈。堆栈基本上保存了所有访问过的节点,并能够返回它所走的路径。 Iterative DFS vs Recursive DFS and different elements order 给出了一个例子。

    【讨论】:

    • 这似乎正是我正在寻找的。由于我们将不得不使用堆栈,我想知道它是否值得。感觉就像它剥夺了使用迭代方法的优势。
    • “[...] 使用 迭代 方法的优势。”你的意思是递归吗?无论如何:链接问题中描述了优点和缺点。
    • 嗯,我发现迭代的优势在于它不使用系统堆栈。如果我必须自己使用堆栈并且失去可读性,那么使用迭代方法似乎没有多大意义。我在理论方面不是很好,我几乎是自学成才的,所以也许我弄错了。
    • 我认为关键是要正确地对堆栈中的项目进行排序(反向!)。就我个人而言,我更喜欢迭代方法,b/c 我认为它可能更容易调试,而且它可以移植到例如VHDL,但这可能无关紧要;)
    • 感谢您的帮助!非常感谢。
    【解决方案2】:

    对于大多数遍历一棵树的算法,如果您想以非递归方式制定它们,您将需要一个额外的数据结构。对于 depth first 遍历(如您的情况),您通常会使用 stack(对于 breadth first 遍历,queue 被使用...)

    在伪代码中,打印树看起来像

    function print_tree(tree_vector)
      s = new stack<int>()
      s.push(0)
      while (!s.empty())
        index = s.pop()
        print (tree_vector[index])
        left = 2*index + 1
        right = 2*index + 2
        if (right < tree_vector.size())
          s.push(right)
        if (left < tree_vector.size())
          s.push(left)
      end while
    end function
    

    请注意,此堆栈隐含地表示编译器在进行递归调用时内部使用的调用堆栈。

    【讨论】:

    • 非常明确的答案,它也解决了我对塞巴斯蒂安回答的担忧。令人惊讶的是,可读性并没有太大损失。
    • 顺便说一句,我不确定,因为这是我第一次看到这个算法,但也许它应该检查右边然后检查左边?
    • 你是对的:为了获得与原始算法相同的行为,应该交换条件检查的顺序......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多