简体   繁体   English

查找多路树的高度

[英]Finding the height of a multiway tree

How do you find the height of a multi-way tree? 您如何找到多向树的高度? If I wanted to find the height of a binary tree, I could do something like this: 如果我想找到二叉树的高度,可以执行以下操作:

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

But I am not sure if I can apply a similar recursive method to a multiway tree. 但是我不确定是否可以将类似的递归方法应用于多路树。

The general case would be: 一般情况是:

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

This depends on how the child nodes are stored. 这取决于子节点的存储方式。 Lets assume for a second that they are stored in a vector. 让我们假设它们存储在向量中。 You could then use the following to calculate their height. 然后,您可以使用以下内容计算其高度。

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

就其价值而言(几乎一无所获),此问题在像SML这样的纯功能语言中得以完美呈现:

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

Isn't it '1 + maximum height of sub-tree starting from any of the child nodes of the (current) root node'? 是不是“(1 +从(当前)根节点的任何子节点开始的子树的最大高度)”?

Note that the binary tree is just a special case of the multi-way tree where the child nodes are known to be the left child and the right child. 请注意,二叉树只是多路树的一种特殊情况,其中子节点被称为左子节点和右子节点。 The result is zero if the root node pointer is null. 如果根节点指针为空,则结果为零。

if non-null: 如果非null:

  • find the height of each of the children 找出每个孩子的身高
  • take the maximum 最大限度地利用
  • add 1 加1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM