Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e ( 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)
like image 998
Aarav Avatar asked Mar 03 '26 11:03

Aarav


1 Answers

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
like image 171
fishiwhj Avatar answered Mar 04 '26 23:03

fishiwhj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!