Review the basic data structures implemented in Python, which includes:
Queue
Stack ……
These structures are constructed by basic data type (List) . In this section, we review Tree.
Trees are used in many areas of computer science, including operating systems, graphics, database systems, and computer networking.
Two Definitions of a tree:
involves nodes and edges, with the basic vocabulary like “sibling, leaf, level, height, subtree”;
a recursive definition: very useful, use “subtree” to abstractly define tree structure
The key decision of implementing a tree is choosing a good internal storage technique. Two techniques:
“list of lists”
“nodes and references”
See the example below:
list of lists
To create this simple tree structure, I can write the following Python function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def buildthistree(a,b,c,d,e,f): # start from the root r = binary_tree(a) insert_left(r,b) insert_right(r,c) l = get_left_child(r) insert_right(l,d) ri = get_right_child(r) insert_left(ri,e) insert_right(ri,f) return r
The basic building functions for defining a tree data structure are:
nodes and references: this representation more closely follows the object-oriented programming paradigm
Both the left and right children of the root are themselves distinct instances of the BinaryTree class. Based on this recursive definition for a tree, it allows us to treat any child of a binary tree as a binary tree itself. The Python code for building a tree via “nodes and references” is: