Bing Gan
Bing Gan

Reputation: 455

python how to implement a list into a tree?

I have a list of data indicates what direction is going next like:

[[0,1,0,0,1],[0,0,1],[0,0],[0,1,1,1,0]]

I want to implement this data into a tree structure like: enter image description here

The number inside the node is how many people walked on this direction.

I have a Tree class that I write myself like this:

class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = 0
def insert(self,num):
    self.data = self.data + 1
    if num == 0:
        if self.left == None:
            self.left = Tree()
        return self.left
    elif num == 1:
        if self.right == None:
            self.right = Tree()
        return self.right

How can I do this? I tried to make it in a recursive way but turns out it's not saving under root but build_tree which is a variable that I tried to make as the recursive pointer.

root = Tree()
for route in data:
    build_tree = root
    for i in range (0,len(route)):
        num = route[i]
        build_tree = build_tree.insert(num)

Thanks!

Edit: This code actually works just like Blender said in comment. I think I had something wrong when I implemented it to a more complex code.

Also thanks John La Rooy for the suggestion and Kevin K. for the example!

Upvotes: 2

Views: 128

Answers (1)

Kevin K.
Kevin K.

Reputation: 1397

Try making a separate class for the node like so

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

Then in your Tree class initialize self.root and declare your functions with recursion within Tree

Edit: Here is an example.

Upvotes: 2

Related Questions