tags:

views:

69

answers:

2

I have a working snippet to use for a regular tree comprising nodes. Now I just need to fiddle with it to work for 2-3-4 trees, which should be easier, since each path is the same distance, since it's balanced, right?

Methods I have at my disposal include getNextChild(), split(), and of course insert().

public int height() {
    return (height(root));
}

private int height(TNode localRoot) {
    if(localRoot == null) {
        return 0;
    }
    else {
       //Find each sides depth
       int lDepth = height(localRoot.leftChild);
       int rDepth = height(localRoot.rightChild);

       //Use the larger of the two
       return (Math.max(lDepth, rDepth) + 1);
    }
}
+1  A: 
public int height ()
{
    TNode cur = root;
    int depth = -1;

    while ( cur != null )
    {
        cur = cur.getChild( 0 );
        depth++;
    }

    return depth;
}
poke
should add a check to make sure root is not null
Woot4Moo
@Woot4Moo: Good catch, updated to iterate differently (and return a height of -1 when the tree is empty).
poke
it should probably be: `return ++depth;` so you don't return `0` if it is depth of `1`
Woot4Moo
A tree has a height of 0 when there is just the root.
poke
This is either giving me an array out of bounds, or with some slight adjustments keeps returning me 2..I have getChild which takes in intChildNumOr getParent which is parameterless..
John Redyns
Oh well, you didn't tell us how to access the childs of a node before; have adjusted my answer, I guess it should work like that.
poke
A: 

If it's balanced, you should just be able to recurse down one side of the tree to determine the height.

Jeremy