【问题标题】:How is this program a pre-order traversal?这个程序是如何进行预购遍历的?
【发布时间】:2014-11-01 00:46:08
【问题描述】:
int count(Node node) {

  if (node == null)
      return 0;

  int r = count (node.right);
  int l = count (node.left);

  return 1 + r + l;
}

此函数返回以节点为根的二叉树中的节点数。有几篇文章说这是前序遍历,但对我来说这看起来像是后序遍历,因为我们在访问根之前访问了左右部分。我在这里错了吗?还是我的“访问”概念有问题?

【问题讨论】:

    标签: java algorithm tree binary-tree


    【解决方案1】:

    在这段代码中,没有在每个节点上进行实际处理,因此前序遍历和后序遍历之间没有区别。如果有处理,区别是:

    预购

    int count(Node node) {
    
      if (node == null)
          return 0;
    
      process(node);    
    
      int r = count (node.right);
      int l = count (node.left);
    
      return 1 + r + l;
    }
    

    下单

    int count(Node node) {
    
      if (node == null)
          return 0;
    
      int r = count (node.right);
      int l = count (node.left);
    
      process(node);    
    
      return 1 + r + l;
    }
    

    (实际上,在这些情况下,与您的代码不同,您可能希望在 node.right 之前递归 node.left,以保留处理子项的传统从左到右顺序。)

    【讨论】:

      【解决方案2】:

      计算节点是很难说算法是预排序还是后排序的情况,因为我们不知道“何时”我们为当前节点“计数”1。

      但如果我们将大小写改为打印,它就会变得清晰:

      预购:

      int visit(Node node) {
        ...
        node.print();          // pre-order  : root cames first
        visit(node.left);
        visit(node.right);
        ...
      }
      

      下单

      int visit(Node node) {
        ...
        visit(node.left);
        visit(node.right);
        node.print();          // post-order  : root cames last
        ...
      }
      

      如您所见,我们可以说哪个 print() 先出现。 通过计数我们不能说根是否在子树之前被计数(+1)。

      这是约定俗成的问题。

      【讨论】:

        【解决方案3】:

        我们可以说这是 pre-order 遍历,因为 count 函数应用于节点 before 而不是其子节点。

        但是这个问题相当棘手,因为您使用的是直接递归,在同一个函数中同时执行遍历和“动作”。

        【讨论】:

          【解决方案4】:

          是的。您对已访问的概念是错误的!这里访问意味着你在当前节点,然后试图遍历树。计数首先在“根”进行,然后是您的计数权利,然后是左侧,所以是的,它是预购的。

          【讨论】:

          • 我想如果它是return r + l + 1; 那么它会是postorder? :)
          • 什么是后序遍历的例子?
          猜你喜欢
          • 2016-04-22
          • 2017-03-05
          • 1970-01-01
          • 2012-09-21
          • 1970-01-01
          • 2014-07-07
          • 1970-01-01
          • 2014-09-18
          • 1970-01-01
          相关资源
          最近更新 更多