简体   繁体   中英

How to create a simple non-binary tree from a list of given nodes in Python

I suppose this is quite a simple problem for experienced ones. It's my first time learning about tree structure so it is not simple. Problem is the following:

A list is given of n elements as follows:

4 -1 4 1 1

and this relates to indexes of an n-sized list as:

4 -1 4 1 1 (parent)

0 1 2 3 4 (node)

In essence, tree needs to be created where value of the node has parent which is above it. If a node has parent of value -1, that node is root.

So tree from the above should look something like this:

Root 1, his children are

3(has no children) and

4(has children 0 and 2).

After that I need to use a simple depth-first algorithm to determine tree depth, and input to this algorithm is the actual tree. Instructions mention that I can build a tree in a list. Now I am completely lost because I don't know which structure use to build a tree and how to use it? Should it be a list? Or a class? Final tree is a list containing all the children, or is it an instance of a class containing all children instances? This is my main problem, after that I think I'm able to implement the depth algorithm.

Ok so I figured it out, I created a class for nodes and a function which will store these classes instances (actual nodes) into array. Index of each nodes is actual value of the node, and each node has variable which stores it's children. In the end the function return root node which has stored all other nodes as its descendants. Now this newly created function createTree can be used to create a tree and traverse it or determine its depth or whatever is the need.

class Node():

    def __init__(self,name): 
        self.children = []
        self.name = name 

    def addChild(self, child):
        self.children.append(child)

    def returnChildren(self):
        return self.children

    def getName(self): 
        return self.name 

def createTree(elements):

    list_of_nodes = []

    for i in range(len(elements)):

        list_of_nodes.append(Node(i))


    for i in range(len(elements)):

        if elements[i] == -1:
            root = list_of_nodes[i]

        else:
            list_of_nodes[elements[i]].addChild(list_of_nodes[i])

    return root

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