【问题标题】:Finding the height of a multiway tree查找多路树的高度
【发布时间】:2009-06-25 14:16:46
【问题描述】:

如何求多路树的高度?如果我想找到二叉树的高度,我可以这样做:

int height(node *root) {
  if (root == NULL)
    return 0;
  else
    return max(height(root->left), height(root->right)) + 1;
}

但我不确定是否可以将类似的递归方法应用于多路树。

【问题讨论】:

    标签: c++ data-structures tree multiway-tree


    【解决方案1】:

    一般情况是:

    int height(node *root)
    {
        if (root == NULL)
            return 0;
        else {
            // pseudo code
            int max = 0;
            for each child {
                int height = height(child);
                if (height > max) max = height;
            }
            return max + 1;
        }
    }
    

    【讨论】:

    • 这不起作用。在 0 个孩子的情况下,您将返回负高度。
    • 由于对高度的多次调用,您还多次在树上行走。这是非常低效的。
    • @jjnguy,不用担心。只是希望 OP 获得正确的行为。
    【解决方案2】:

    这取决于子节点的存储方式。让我们假设它们存储在一个向量中。然后,您可以使用以下方法计算它们的高度。

    int height(node* root ) {
      if ( !root ) {
        return 0;
      }
      int max = 0;
      for ( vector<node*>::const_iterator it = root->children.begin();
            it != root->children.end();
            it++ ) {
        int cur = height(*it);
        if ( cur > max ) {  
          max = cur;
        }
      }
      return max+1;
    }
    

    【讨论】:

      【解决方案3】:

      对于它的价值(几乎没有),这个问题在像 SML 这样的纯函数式语言中表现得很漂亮:

      fun height Node(children) = (foldl max -1 (map height children)) + 1
      

      【讨论】:

        【解决方案4】:

        如果非空:

        • 找出每个孩子的身高
        • 取最大值
        • 加1

        【讨论】:

          【解决方案5】:

          不是'1 + 从(当前)根节点的任何子节点开始的子树的最大高度'吗?

          请注意,二叉树只是多路树的一个特例,其中子节点已知为左孩子和右孩子。如果根节点指针为空,则结果为零。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-12-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-03-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多