Common data structure of binary tree and four tree traversal methods

1. Tree

         We choose a data structure not only to be able to store data, but also to reflect the relationship between the data. At present, there are mainly three types of data relationships: one-to-one, one-to-many, and many-to-many; before we discussed linear lists (arrays, linked lists, stacks, queues), in which the elements have a one-to-one relationship, passing between elements Connect left and right to express data. In order to express data with a one-to-many relationship, we introduced the concept of a tree. The key to mastering the tree is to master this continuously extending one-to-many relationship.

                                               

          Below we introduce several conventions and concepts:

                Node : Each element in the tree is called a node

                Parent node (parent node) : the node that produces other nodes (that is, the one in one-to-many), which is often a local relative relationship, as shown in Figure A, B, C, and D, where A is B, C, D Parent node

                Child nodes : nodes generated by other nodes (that is, many in one-to-many), which is also a local relative relationship, as shown in Figure A, B, C, and D, B, C, and D are the child nodes of A

                Root node : The topmost node in a tree (without any parent node). This is an absolute relationship relative to the entire tree. As shown in A.

                Leaf node : A node without any child nodes. This is also an absolute relationship, relative to the entire tree. K, L, F, G, M, I, J in the picture

                Subtree : The small trees contained in the big tree. For example, B, E, F, K, and L in the tree above also constitute a tree, called a subtree. A tree is often composed of multiple subtrees.

                 Empty tree : a tree without any nodes

                 Degree : The number of subtrees owned by a node is called the degree of the node. That is, the branch tree corresponding to the node. The largest degree among the connected nodes is called the degree of the tree.

                 Level : The number of nodes passed from the root node to the farthest child node. For example, A, B, E, and K in the above figure are the farthest paths, and the level of the tree is 4.

                 Ordered tree and unordered tree : There is an order between sibling nodes, which is called an ordered tree. Otherwise, it is an unordered tree. The picture above is an ordered tree. Please note that the order here does not mean the size relationship between sibling nodes. It means more that this kind of tree is sensitive to the order of sibling elements . If the sibling nodes are arranged in a different order, it represents a different tree. For example: 12 and 21 are different. Although they have two elements 1, 2, but they are sensitive to the order, that is, order; 1+2 and 2+1, if the result is evaluated alone, then It is disorderly. In addition, whether it is ordered or disordered, it is for sibling nodes, and the parent and child nodes are all ordered.

                 Forest : Multiple trees that you don't want to cross are called forests. As shown in the figure above, the collection of subtrees with nodes B, C, and D is a forest. Many trees form a forest, and large trees often contain forest.

            Summary: A tree is a data structure that stores one-to-many data, named because its shape is similar to an upside-down tree. The first element in a tree is called the root node, and the element without children is called the leaf node. A collection of trees that you don't want to cross is called a forest. There are multiple trees in the forest, and one tree can also contain the forest. These are concepts that people have agreed upon for unification. At the core, we need to master the one-to-many point, which can be regarded as the seed of the tree, and all forms are issued by him.

2. Binary tree definition

           Binary tree is currently the most widely used tree structure, there is no one. In the interview, it is often a compulsory test, sending sub-items or propositions! Two fork does not mean two stunned children, but refers to the one-to-two data relationship. And it must be an ordered tree ! As shown in the figure below, the specific representation is like Figure a. Each node has two degrees at the end (ie, two branches). It can be seen that each layer has at most 2^{n-1}one node.         

                             

 

3. Full binary tree definition

          The so-called full binary tree means that the binary tree is full (that is, there are elements in all positions). In fact, it is enough to remember the above, if you really want to push, you can get a few features. 1. The number of leaf nodes is 2^{n-1} ; 2. Except for the last layer, the number of other nodes is 2^{n-1}-1;

                                          

4. Complete Binary Tree Definition

             A complete binary tree is a somewhat incomplete full binary tree. If a full binary tree is perfect, it is perfect, perfect, seven, etc. We see that the last level of nodes in a complete binary tree is not required to be filled. You can think of a full binary tree as a special kind of complete binary tree.

            The data structure heap we mentioned in the previous sections is a complete binary tree. Nagging about its node calculation logic again, we define the subscript to start from 0, and the subscript of the parent node is i. Then the subscript of the left child node is, and the subscript of the 2i + 1right child node is 2i + 2. Given that the subscript of the child node is i, then the subscript of the parent node is floor((i-1)/2).

                                                   

 

5. Python implementation of the basic structure of the binary tree

         There are two ways to implement a binary tree, sequential structure (a fixed-size memory space) and chain structure. This article uses lists in python to implement a simple binary tree. Basic ideas: 1. Create a node class, containing three attributes val (value of the node), left (left child node), right (right child node) 2. Add all nodes to a list 3. Traverse the list and find The left and right nodes of each element and assign values.

class Node:
    def __init__(self,value,left=None,right=None):
        self.val = value
        self.left = left
        self.right = right
    def show(self):
        print(self.val,end='\t')

  6. Preorder traversal of binary tree

           Preorder traversal is a depth-first traversal algorithm from left to right. The order of traversal is root node -> left subtree -> right subtree. It is called preorder traversal because the root node is the first to be traversed (personal understanding) we use two ways to achieve this. The first recursive method is relatively simple to understand. If it is the left child node, output the current node and continue to exhaust its child nodes. Then exhaust the right child nodes. The second way is to use the stack, first push the right child node into the stack, then push the left child node into the stack, pop the left child node, and continue to traverse until there is no left child node and then pop the right child node.

    # 前序遍历 递归实现
    # 根节点——>左子节点——>右子节点
    def pre_order_recursion(self,Node):
        Node.show()
        if Node.left:
            self.pre_order_recursion(Node.left)
        if Node.right:
            self.pre_order_recursion(Node.right)
    # 前序遍历 使用栈来实现
    def pre_order(Node):
        result = []
        stack = [Node]
        while stack:
            node = stack.pop()
            if node:
                result.append(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return result

7. In-order traversal of binary tree

         Mid-order traversal is also a depth-first algorithm. Its order is left subtree -> root node -> right subtree. Because the follow node is output in the middle, it is called mid-order traversal (personal understanding) . For the specific code implementation, we only need to slightly modify the pre-order traversal, as follows.

def mid_order_recursion(Node):
    if Node.left:
        mid_order_recursion(Node.left)
    Node.show()
    if Node.right:
        mid_order_recursion(Node.right)

8. Post-order traversal of binary tree

          Post-order traversal is also a depth-first algorithm. Its order is left subtree -> right subtree -> root node. Because the root node is the last output, it is called post-order traversal (personal understanding). The specific code is as follows, Just slightly modify the above.

def post_order_recursion(Node):
    if Node.left:
        post_order_recursion(Node.left)
    if Node.right:
        post_order_recursion(Node.right)
    Node.show()

8. Level traversal of binary tree

       Level traversal is a breadth-first algorithm, that is, starting from the root node from top to bottom, and traversing each layer from left to right. The idea is to add the current layer node to the list from top to bottom, and then add its left and right child nodes to the list, continuously looping.

def lever_order_recursion(Node):
    result = []
    current_node = [Node]
    while len(current_node) > 0:
        next_node = []
        for node_c in current_node:
            result.append(node_c.val)
            if node_c.left is not None:
                next_node.append(node_c.left)
            if node_c.right is not None:
                next_node.append(node_c.right)
        current_node = next_node
    return  result

to sum up:

           In this article, we first talked about the concept of a tree, a data structure that represents one-to-many data relationships; from it, an ordered tree with at most two child nodes was introduced. Then two special binary trees are introduced: complete binary trees and full binary trees. Full binary trees are also a special kind of complete binary trees. Finally, we introduce the construction of binary tree and four commonly used traversal methods: preorder traversal (first traverse the root node, then traverse the left subtree, and finally the right subtree), middle order traversal (first traverse the left subtree, then traverse the root node) , Traverse the right subtree last) and subsequent traversal (first traverse the left subtree, then traverse the right subtree, and finally traverse the root node), these three algorithms are depth-first algorithms. Finally, we introduced level traversal, a breadth-first algorithm that traverses data in order from top to bottom and from left to right. The code in this article is implemented using python.

Tea Talk:

         Recommend a poem of my idol to everyone. The words that have touched the Chinese people for more than a thousand years, the extremely plain language, but often make people burst into tears.

        Ten years of life and death are boundless, unforgettable without thinking . Thousands of miles of lonely grave, there is nowhere to say desolate. Even if they meet, they should not know it, dusty face, temples like frost.

  At night, You Meng suddenly returned home, Xiaoxuan window, was dressing. There is nothing but tears. Expected to be broken every year, bright moon night, short Matsuoka.

                                                                                                            "Jiangchengzi·Yimao First Moon 20th Night Dream" by Su Shi

 

 

Guess you like

Origin blog.csdn.net/gaobing1993/article/details/108846491