找到多路树的高度

时间:2009-06-25 14:16:46

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

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

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

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

5 个答案:

答案 0 :(得分:4)

一般情况是:

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;
    }
}

答案 1 :(得分:1)

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

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;
}

答案 2 :(得分:1)

对于它的价值(几乎没有),这个问题在像SML这样的纯函数语言中呈现出色:

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

如果非空:

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