java - 查找树的最大宽度的算法,不使用节点结构

标签 java algorithm recursion groovy binary-tree

我想知道如何计算一棵树的最大宽度。我没有使用典型的叶/节点结构,而是基于来自数据库的数据。我将找到特定“节点”(人)的所有子节点以确定对等线的最大宽度:

     1
    /  \
   2    3
 / | \     \
4  5  6     7 
          /  \
         8    9

所以上面那棵树的最大值是 4。因为我没有使用传统的左/右方法,而且 child 的数量可以大于 2,我该怎么做呢?

一些事情:

  • 这不是家庭作业
  • 我下面的代码生成的最大宽度大约为 3200(我为手头的示例计算的最大值是 22)

这是我目前的代码:

private int calculateWidth(def org, int h) {

    def allContacts = Contact.findAllByOrganization(org)
    List<String> headNodes = findHighestNode(org.id, allContacts )

    Contact contact = Contact.get(Long.parseLong(headNodes.get(0)))
    Person parent = new Person(contact.id, contact.fullName)

    int maxWidth = 0;
    int width;
    int heightOfChart = h;
    int i;

    for(i = 1; i <= heightOfChart; i++)
    {
      width = getWidth(parent, i);

      if(width > maxWidth)
        maxWidth = width;
    }

    System.out.println("The max width is = " + maxWidth)
    return ((NODE_HEIGHT + NODE_OFFSET) * (maxWidth))
}

private int getWidth(Person parent, int level)
{

  List<Person> allChildren = getChildren(parent)

  if(allChildren.size() == 0)
    return 0;

  if(level == 1)
    return 1;

  else if (level > 1) {
    int count = 0
    for(Person child : allChildren) {
        count = count + getWidth(parent, level-1)
    }
    return count
  }
}

最佳答案

我没有真正检查过您的代码,但我会使用广度优先搜索方法。

一些伪代码:

start with list containing just the trees root. call it CurrNodes.
maxWidth = 1;
start with empty list. call it NextNodes.
while(CurrNodes is not empty) {
   get all children of nodes in CurrNodes and add them to NextNodes
   if number of children is > maxWidth, # of children is the new maxWidth
   CurrNodes = NextNodes
   NextNodes = empty.
}

关于java - 查找树的最大宽度的算法,不使用节点结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11954108/

相关文章:

java - 为什么我们在 .class 文件的开头需要一个魔数(Magic Number)?

java - 自动调整 Swing 组件的大小

java - libNFC是否只支持READ、WRITE和COMP_WRITE

javascript - JQuery 在数据之前附加结束标记

javascript - 有关 promise 的详细信息;例子

java - 检查回文字符串

arrays - 查找包含所有元素的最短子数组

algorithm - 一个偏序集的元素是最大的概率?

java - 如何使用 while 循环找到最大整数 (n),使得 n^3 < 12,000

python - 如何使用递归多次划分数字并跟踪迭代?