Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Implementation of Tree structure in Python

Shulou Source: shulou.com Published: 2022-06-02 05:29:14 09月26日 Update

This article mainly introduces "the implementation method of tree structure in Python". In daily operation, I believe many people have doubts about the implementation method of tree structure in Python. Xiaobian consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts of "the implementation method of tree structure in Python"! Next, please follow the small series to learn together!

Binary tree implementation--nested list

Binary tree is implemented using recursive nested lists, each node is implemented by a list with three elements

[root, left, right]

First element in the list: root node (is a data item)

Second element in the list: left subtree (also a list)

Third element in the list: right subtree (also a list)

If it is a leaf node, it is an empty table.

Examples:

The advantages of using nested list method to realize binary tree:

The subtree has the same structure as the tree and is a recursive implementation.

This method can be easily extended to multi-tree by adding elements to the list

A nested list binary tree implementation requires defining some functions to satisfy the binary tree operation requirements:

binary_tree: Create a binary tree with only root nodes

insert_left/insert_right: Insert a new node into the tree

get_root_value/set_root_value: Get/modify root node

get_left_tree/get_right_tree: Get left/right subtree

Implementation of linked list of binary tree

Binary tree implementation can also be used to implement the linked list of nodes

In addition to data items, each node also stores indexes of left and right subtrees.

For the root node root, this is a relative concept, not necessarily refers to the entire root node of the binary tree, want to add left and right subtrees to any node, you can first obtain the target node, that node as the root node

At this point, the study of "the implementation method of tree structure in Python" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Tags: Nodes methods subtrees structures elements learning three data data items more recursion help utility same next advantages functions leaves that is articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux macOS MariaDB NVidia Xiaomi