Tree data structure establishment

Time:2021-10-23

Tree data structure establishment

Many times we need a tree structure to manage our data, such as the following

  • File structure: computer directory file
  • House structure: building area facility
  • Library structure: Library – category – Books

The tree structure is composed of nodes, and several basic attributes are necessary

  • Parent node is used to link parent items. You can find the upper level from the lower level of the tree structure. There is only one item set
  • Child nodes are used to link sub items. You can find the lower level from the upper level of the tree structure. There can be multiple settings
  • The node name is used to represent the node and is represented by human recognizable words. Therefore, it can be repeated and cannot be used to represent the node in the data structure
  • Node value, which is used to store various information of the node itself
  • Node key is used to represent nodes. This key value does not need to be recognized by human beings, but in order to represent each node, this key value must be unique and non repeatable

In addition to the information of each node, a dictionary is needed to record all nodes



Class definition of tree structure node

So what we need to do now is to create a node class

  1. Definition of class / node (class)
class Node():
  1. Class variable of node record table = empty dictionary {node key: node,…}
elements = {}
  1. Function / start – parameter is node name and node value (_init_)
    • Attribute. Node name = node name
    • Attribute. Node value = node value
    • Attribute. Parent node = none
    • Attribute. Child node = empty list
    • Attribute. Node key = call node key to automatically generate function
def __init__(self, name, values=None):
        self.name = name
        self.parent = None
        self.children = []
        self.values = {} if values is None else values
        self.key = self.get_key()
        Node.elements[self.key] = self
  1. Function / node keys are generated automatically (0 is reserved for the tree root as the top layer)
    • Start with 1 and add up. Find a nonexistent node key in the node record table
def get_key(self):
        key = 0
        while key in Node.elements:
            key += 1
        return key
  1. Function / add child node – the parameter is the node key of the child node
    • Add child node key to child node list
    • According to the child node key, find the child node in the node record table, and the parent node of the child node is the node key
def add_child(self, child):
        key = child.key
        self.children.append(key)
        Node.elements[key].parent = self.key
    def add_children(self, children):
        for child in children:
            self.add_child(child)
  1. Function / remove child node – the parameter is the node key of the child node
    • Child node list delete child node key
    • According to the child node key, find the child node in the node record table, and set the parent node of the child node to none
def remove_child(self, key):
        if key in self.children:
            self.children.remove(key)
            Node.elements[key].parent = None
    def remove_children(self):
        for key in self.children:
            self.remove_child(key)
  1. String form of function / display node (_repr_)
    • Display node name + node value
    • Cycle down the list of child nodes to find the node name + node value of each child node

      Until there are no child nodes
def get_string(self, key, i=0):
        node = Node.elements[key]
        result = ' '*i + node.name + ' ' + str(node.values) + '\n'
        for child in node.children:
            result += self.get_string(child, i+2)
        return result

    def __repr__(self):
        return self.get_string(self.key).strip()



Mode of use

  1. Establish node / tree data structure
chairs = [Node(f'Chair {i}', values={'material':'metal', 'size':'medium'}) for i in range(12)]
table_1 = Node('Table 1', values={'material':'wood', 'size':'medium'})
table_1.add_children([chairs[i] for i in range(4)])
table_2 = Node('Table 2', values={'material':'wood', 'size':'large'})
table_2.add_children([chairs[i] for i in range(4, 12)])
kitchen = Node('Kitchen 1', values={'area':20})
kitchen.add_child(table_1)
kitchen.add_child(table_2)
bedrooms = [Node(f'Bedroom {i}', values={'size':'double'}) for i in range(3)]
house = Node('House 1', values={'cost':1200000, 'area':100, 'city':'Zuhai'})
house.add_child(kitchen)
house.add_children(bedrooms)
  1. Display results
>>> house
House 1 {'cost': 1200000, 'area': 100, 'city': 'Zuhai'}
  Kitchen 1 {'area': 20}
    Table 1 {'material': 'wood', 'size': 'medium'}
      Chair 0 {'material': 'metal', 'size': 'medium'}
      Chair 1 {'material': 'metal', 'size': 'medium'}
      Chair 2 {'material': 'metal', 'size': 'medium'}
      Chair 3 {'material': 'metal', 'size': 'medium'}
    Table 2 {'material': 'wood', 'size': 'large'}
      Chair 4 {'material': 'metal', 'size': 'medium'}
      Chair 5 {'material': 'metal', 'size': 'medium'}
      Chair 6 {'material': 'metal', 'size': 'medium'}
      Chair 7 {'material': 'metal', 'size': 'medium'}
      Chair 8 {'material': 'metal', 'size': 'medium'}
      Chair 9 {'material': 'metal', 'size': 'medium'}
      Chair 10 {'material': 'metal', 'size': 'medium'}
      Chair 11 {'material': 'metal', 'size': 'medium'}
  Bedroom 0 {'size': 'double'}
  Bedroom 1 {'size': 'double'}
  Bedroom 2 {'size': 'double'}

Note: deleting nodes and moving nodes can be done, which is complex. I won’t elaborate here

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Jason Yang

Recommended Today

SQL statement of three-level linkage of provinces, cities and counties

The first is the table creation statement Copy codeThe code is as follows: CREATE TABLE `t_address_province` ( `id` INT AUTO_ Increment primary key comment ‘primary key’,`Code ` char (6) not null comment ‘province code’,`Name ` varchar (40) not null comment ‘province name’)Engine = InnoDB default charset = utf8 comment = ‘province information table’; CREATE TABLE […]