【问题标题】:Height of 2-3-4 tree2-3-4树的高度
【发布时间】:2011-05-02 02:03:33
【问题描述】:

我有一个有效的 sn-p 可用于包含节点的常规树。现在我只需要摆弄它来处理 2-3-4 棵树,这应该更容易,因为每条路径的距离相同,因为它是平衡的,对吧?

我可以使用的方法包括getNextChild()split(),当然还有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);
    }
}

【问题讨论】:

  • 可以摆脱左右深度并使用一行获取下一个孩子吗?
  • @John 我认为这打破了树的概念
  • 是的,但是关于仅查找和返回高度,我走哪条路并不重要?如果他们都返回相同的?
  • @John 我相信这是正确的,当然除非你不正确地实现了 2-4 树:)
  • @Woot4Moo:B 树中的外部节点根据定义始终具有相同的高度。

标签: java tree height


【解决方案1】:
public int height ()
{
    TNode cur = root;
    int depth = -1;

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

    return depth;
}

【讨论】:

  • 应添加检查以确保 root 不为空
  • @Woot4Moo:很好的捕获,更新为不同的迭代(当树为空时返回高度 -1)。
  • 它可能应该是:return ++depth;,所以如果它的深度是1,你就不会返回0
  • 只有根时,树的高度为 0。
  • 这要么给了我一个超出范围的数组,要么通过一些细微的调整不断返回我 2.. 我有 getChild 接受 intChildNum 或 getParent 是无参数的..
【解决方案2】:

如果它是平衡的,你应该能够沿着树的一侧递归来确定高度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2012-01-22
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多