开发者

Height of 2-3-4 tree

开发者 https://www.devze.com 2023-01-23 01:19 出处:网络
I have a working snippet to use for a regular tree comprising nodes. Now I just need to fiddle wi开发者_如何学Pythonth it to work for 2-3-4 trees, which should be easier, since each path is the same d

I have a working snippet to use for a regular tree comprising nodes. Now I just need to fiddle wi开发者_如何学Pythonth 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);
    }
}


public int height ()
{
    TNode cur = root;
    int depth = -1;

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

    return depth;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消