2

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.

Casey
  • 41,449
  • 7
  • 95
  • 125
Bramble
  • 1,395
  • 13
  • 39
  • 55

5 Answers5

4

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;
    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jjnguy
  • 136,852
  • 53
  • 295
  • 323
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;
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

For what it's worth (almost nothing), this problem renders beautifully in pure-functional languages like SML:

fun height Node(children) = (foldl max -1 (map height children)) + 1
Daniel Spiewak
  • 54,515
  • 14
  • 108
  • 120
0

Isn't it '1 + maximum height of sub-tree starting from any of the child nodes of the (current) root node'?

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

if non-null:

  • find the height of each of the children
  • take the maximum
  • add 1
Jason S
  • 184,598
  • 164
  • 608
  • 970