views:

437

answers:

5
+1  Q: 

Multi-way tree

How do you find the height of a multi-way tree? A binary tree looks something like this...

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

I cant figure it for multi-way.

A: 

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
A: 

if non-null:

  • find the height of each of the children
  • take the maximum
  • add 1
Jason S
+4  A: 

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;
    }
}
jjnguy
This doesn't work. In the case of 0 children, you will return a negative height.
JaredPar
You also walk the tree many times because of the multiple calls to height. This is very inefficient.
JaredPar
Whoops....ty .
jjnguy
It was sudo code...I know it is not the exact right way to do it...
jjnguy
edited .
jjnguy
p.s. I don't know c++ much at all....
jjnguy
@jjnguy, no worries. Just wanted the OP to get the right behavior.
JaredPar
good call .
jjnguy
+1  A: 

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
+1  A: 

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