简体   繁体   中英

Recursive function that print a tree

I have a tree object:

a = <albero.Albero at 0x21fbc003cf8>

These method:

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

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

I created the tree but now is the problem. I want to return an output string like this:

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

I think that is possible only with recursive function. Another example:

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

for this tree I try to create this list:

['  80  ',' _|_  ','|   | ','70  90']

Any ideas?

Not sure how your Albero (Tree) class is designed so I made a fake one for testing. I believe you will be able to adapt this function to your class:

Fake Tree Node class for testing:

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)

The recursive function treeLines() expects the root node as first parameter and a function to get the identifier and children of a node as second parameter. This makes the function generic and able to handle any class that has a parent-child relationship to itself.
The treeText() function uses the result of treeLine() to build a single string with an end of line character between each line.

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)) )

This prints:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM