查找树的高度,其中输入树可以具有任意数量的子代

时间:2019-07-03 08:05:13

标签: python recursion tree tuples

我的问题的一部分是编写一个确定树的高度的函数。

这是我当前的功能,

def tree_height(node): 
  parent, children = node
  max_height = 0
  for child in children:
    height = tree_height(child)
    if height > max_height:
      max_height = height
  return max_height 

但它只会返回0。

*注意:只能有一个输入参数,即节点*

对于

tree = ("supercalifragilisticexpialidocious",(("a",(("b",(("candy",()),)),("onomatopoeia",()),)),("d",(("egg",(("f",()),)),)),))

输出应为

3

2 个答案:

答案 0 :(得分:2)

您永远不会增加 SXSSFWorkbook workbook = new SXSSFWorkbook(100); SXSSFSheet sheet = workbook.createSheet(); String[] optionsArray = new String[] {"1000.00","2000.00"}; int no_of_rows = 35000; for(int i=0;i<=no_of_rows;i++) { SXSSFRow row1 = sheet.createRow(i); SXSSFCell r1c1 = row1.createCell(0); DataValidationConstraint constraint1 = sheet.getDataValidationHelper().createExplicitListConstraint(optionsArray); CellRangeAddressList addressList1 = new CellRangeAddressList(i, i, 0, 0); DataValidation dataValidation1 = sheet.getDataValidationHelper().createValidation(constraint1, addressList1); sheet.addValidationData(dataValidation1); r1c1.setCellValue("1000.00"); SXSSFCell r1c2 = row1.createCell(1); DataValidationConstraint constraint2 = sheet.getDataValidationHelper().createExplicitListConstraint(optionsArray); CellRangeAddressList addressList2 = new CellRangeAddressList(i, i, 1, 1); DataValidation dataValidation2 = sheet.getDataValidationHelper().createValidation(constraint2, addressList2); sheet.addValidationData(dataValidation2); r1c2.setCellValue("2000.00"); } FileOutputStream fos =new FileOutputStream(new File("c:\\data\\testout.xlsx")); workbook.write(fos); workbook.close(); fos.close(); ,因此递归调用将始终返回0;请记住,您比孩子高出一步。

max_height

您需要“相信”递归:假设def tree_height(node): parent, children = node max_height = 0 for child in children: child_height = tree_height(child) max_height = max(max_height, child_height + 1) return max_height 使您的孩子高了。那么,您的身高就是所有孩子的最大身高加一。

编辑:

更多Python代码:

tree_height(child)

答案 1 :(得分:0)

我认为您的方法正确,但问题是您可能不了解递归height = tree_height(child),因为如果没有子代,它将返回0,最后将返回0(这是您的情况) )

您应该做的是在函数内部放置另一个参数,该参数将计算深度

def tree_height(node, counter): 
    parent, children = node
    max_height = 0
    for child in children:
        height = tree_height(child, counter + 1)
        if height > max_height:
            max_height = height
    if max_height == 0:
        return counter
    return max_height

尝试一下此代码,下次将其写/画在纸上以查看它的功能+不要在此处张贴您的算法作业:)