Bing Gan Bing Gan -4 years ago 108
Python Question

python how to implement a list into a tree?

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


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 = 0
def insert(self,num): = + 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
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)


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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download