打印树的递归函数

时间:2019-03-19 21:39:34

标签: python string recursion tree

我有一个树对象:

WITH CTE_1 AS(SELECT [server_name]
          ,[sessionID]
          ,[user]
          ,[ElapsedTime]
          ,ROW_NUMBER() OVER(PARITION BY sessionID ORDER BY sessionID) rn
    from table) SELECT * FROM CTE_1 WHERE rn = 1

这些方法:

a = <albero.Albero at 0x21fbc003cf8>

我创建了树,但是现在是问题所在。我想返回这样的输出字符串:

a.f #print out a list of sons object
[<albero.Albero at 0x21fbc003cc0>]

a.id #print out the value of a
"03"

我认为只有递归函数才有可能。另一个示例:

'''           05              
 _____________|_____________  
|             |             | 
02            04            06
|    _________|_________      
01  |     |     |   |   |     
    01    02    09  08  02    
         _|_                  
        |   |                 
        03  06                '''

为此树,我尝试创建此列表:

'''04
| 
05
| 
01
| 
06
| 
03'''

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

不知道您的Albero(Tree)类是如何设计的,所以我制作了一个假的进行测试。我相信您将能够将此功能调整为适合您的班级:

用于测试的假树节点类:

class Albero:
    def __init__(self,id,parent=None):
        self.id = id
        self.f = []
        if parent: parent.f.append(self)

n05  = Albero("05")
n02  = Albero("02",n05)
n04  = Albero("04",n05)
n06  = Albero("06",n05)
Albero("01",n02)
Albero("01",n04)
n02 = Albero("02",n04)
Albero("09",n04)
Albero("08",n04)
Albero("02",n04)
Albero("03",n02)
Albero("06",n02)

递归函数treeLines()期望将根节点作为第一个参数,并将该函数获取节点的标识符和子代作为第二个参数。这使该函数具有通用性,并能够处理与其自身具有父子关系的任何类。
treeText()函数使用treeLine()的结果来构建单个字符串,并在每行之间使用行尾字符。

def treeLines(node,getInfo):
    nodeId,nodeChildren = getInfo(node)
    subNodes   = [treeLines(child,getInfo) for child in nodeChildren]
    widths     = [ len(childText[0]) for childText in subNodes ]
    totalWidth = sum(widths) + 2*len(widths) - 1
    totalWidth = max(totalWidth,len(nodeId))
    nodeLine   = nodeId.center(totalWidth," ")
    result     = [nodeLine]
    if not nodeChildren: return result
    linksLine   = "  ".join("|".center(width," ") for width in widths)
    linksLine   = linksLine.center(totalWidth," ")
    leftIndent  = linksLine.index("|") + 1
    rightIndent = linksLine[::-1].index("|") + 1
    spanWidth   = totalWidth - leftIndent - rightIndent - 1
    leftSpan    = nodeLine.index(nodeId)-leftIndent+(len(nodeId)-1)//2
    rightSpan   = spanWidth - leftSpan   
    spanLine    = " "*leftIndent + "_"*leftSpan + "|" + "_"*rightSpan + " "*rightIndent
    if len(nodeChildren) > 1 : result.append(spanLine)
    result.append(linksLine)
    maxHeight   = max(len(subNode) for subNode in subNodes)
    subNodes    = [ subNode + [" "*len(subNode[0])]*(maxHeight-len(subNode)) for subNode in subNodes ]
    result     += ["  ".join([subNode[i] for subNode in subNodes]).center(totalWidth," ") for i in range(maxHeight) ]
    return result  

def treeText(node,getInfo): return "\n".join(treeLines(node,getInfo))

print( treeText(n05,lambda n:(n.id,n.f)) )

此打印:

                05                
  ______________|______________   
 |              |              |  
 02             04             06 
 |    __________|_________        
 01  |      |     |   |   |       
     01     02    09  08  02      
           _|_                    
          |   |                   
          03  06