简体   繁体   中英

How to return all possible paths of random binary tree in Python

I have a random binary tree in the following forms

12

13, 14

29, 26, 89

Each node has two children ie ( 12->(13, 14), 13->(29, 26), 14 ->(26, 89)). Here I need to return all possible paths in the forms [ [12, 13, 29], [ 12, 13, 26], [12, 14, 26], [12, 14, 89]]. I tried with the following code. I have problem with updating list. Thanks in advance.

class Tree:

    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def __str_(self):
        return '%s' % self.data

def makeList(tree, path =[]):
    if(tree != None):
        path.append(tree.data)
        if tree.left:
            path.append(makeList(tree.left, path))
        if tree.right:
            path.append(makeList(tree.left, path))

    return path

root = Tree(12)

root.left = Tree(13)

root.right = Tree(14)

root.right.left = Tree(26)

root.left.right = Tree(26)

root.left.left = Tree(29)

root.right.right = Tree(86)

x = makeList(root)

I don't know how to solve it using a memoized recursion . But I still post my answer since it may solve your problem partly.

def makeList(tree):
    paths = []
    if not (tree.left or tree.right):
        return [[tree.data]]
    if tree.left:
        paths.extend([[tree.data] + child for child in makeList(tree.left)])
    if tree.right:
        paths.extend([[tree.data] + child for child in makeList(tree.right)])
    return paths

When you set this:

def makeList(tree, path =[]):

This empty list after path is not deleted after the execution of the function, if you call makeList a second time without a path parameter, the path list you had at the end of the first call will remain.

Consider the function:

def f(l=[]):
    l.append(17)
    print l

If you keep on calling f() without the parameter l you will get another 17 each time.

[17]
[17, 17]
[17, 17, 17]

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