2

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

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

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

4

5 回答 5

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;
    }
}
于 2009-06-25T14:21:51.477 回答
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;
}
于 2009-06-25T14:23:42.347 回答
1

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

fun height Node(children) = (foldl max -1 (map height children)) + 1
于 2009-06-25T14:26:28.003 回答
0

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

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

于 2009-06-25T14:19:39.577 回答
0

如果非空:

  • 找出每个孩子的身高
  • 取最大值
  • 加 1
于 2009-06-25T14:20:07.877 回答