---Study on the Road (a) Python data structures and algorithms (5) binary search, binary tree traversal

Source: Internet
Author: User

Monologue:

The algorithm is used to find the specified elements, and recently learned two-point lookups and two-tree traversal. Binary search is a prerequisite for searching in order, and the binary tree introduces the concept of tree. The concept of a tree has many small knowledge points and is also a new data structure. Or before the sentiment, need to understand its essence will write a better algorithm.

Two-point Search

Binary search also known as binary lookup, the advantages are less than the number of comparisons, Find Fast, the average performance is good, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent. First, suppose that the elements in the table are arranged in ascending order, comparing the keywords in the middle position of the table with the lookup keywords, and if they are equal, the lookup succeeds; otherwise, the table is divided into the front and the last two sub-tables with the intermediate positional records, and if the middle position record keyword is greater than the Find keyword, the previous child Otherwise, find the latter child table further. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time.

"Binary Find Time Complexity: O (Logn)" "is provided in an ordered list" ' Import time## def binary_search (list, item): # ' ' Non-Recursive implementation ' # # first = 0#  last = Len (list)-# and First <= last: # midpoint = (first + last)//if List[midpoint] = = item:# return true# elif Item < list[midpoint]:# last = midpoint-1# else: # first = midpoint + # return Falsedef binary_search (list, item): "" "Recursive Implementation" "" Print (list) if Le N (list) = = 0:return False else:midpoint = len (list)//2 if list[midpoint] = = Item:r             Eturn True else:if List[midpoint] > Item:return binary_search (list[:midpoint], item) Else:return Binary_search (List[midpoint + 1:], item) If __name__ = = ' __main__ ': # Start time fi Rst_time = Time.time () # Create an ordered list of lis = [1, 2, 5, 6, 7, 8, 9, 17, 156, 678] # list sort print (Binary_search (LIS, 6) ) # End Time Last_time = Time.time () print ("Total%s"% (Last_time-first_time)) 

The concept of tree and tree algorithm tree

A tree is an abstract data type (ADT) or a data structure of an abstract data type that simulates a collection of data of a tree-like nature. It is a set of hierarchical relationships consisting of n (n>=1) finite nodes. It's called a "tree" because it looks like an upside down tree, which means it's rooted up and leaves facing down. It has the following characteristics:

    • Each node has 0 or more child nodes;
    • A node without a parent node is called the root node;
    • Each non-root node has only one parent node;
    • In addition to the root node, each child node can be divided into multiple disjoint subtrees;
Terminology of the tree
    • Node Degree: The number of sub-trees that a node contains is called the degree of the node;
    • Degree of the tree: the degree of the largest node in a tree is called the degree of the tree;
    • leaf node or end node: a zero-degree node;
    • Father node or parent node: If a node contains child nodes, this node is called the parent node of its child nodes;
    • child node or child node: the root node of a subtree containing a node is called a child node of that node;
    • Sibling nodes: nodes with the same parent node are called sibling nodes;
    • The hierarchy of nodes: From the beginning of the root definition, the root is the 1th layer, the root of the child node is the 2nd layer, and so on;
    • The height or depth of a tree: the maximum level of nodes in a tree;
    • Cousin node: The parent node in the same layer of the nodes are each other cousins;
    • Ancestor of a node: all nodes from the root to the branch of the node;
    • Descendants: Any node in a subtree that is rooted in a node is known as the descendant of that node.
    • Forest: The collection of trees that are disjoint by M (m>=0) is called a forest;
Types of Trees
    • Unordered tree: There is no sequential relationship between the child nodes of any node in the tree, which is called the unordered tree, also known as the free tree;
    • Ordered tree: There is a sequential relationship between the child nodes of any node in the tree, which is called ordered tree;
      • Binary tree: A tree with a maximum of two subtrees per node is called a binary tree;
        • Complete binary tree: For a binary tree, suppose its depth is D (d>1). In addition to layer D, the number of nodes in each layer has reached the maximum, and all nodes of layer d are continuously arranged from left to right, so that the two-fork tree is called a complete binary tree, where the definition of full two-tree is the complete binary tree with all the leaf nodes at the bottom;
        • Balanced binary tree (AVL tree): When and only if the height difference of the two subtrees trees of any node is not greater than 1 of the two-fork tree;
        • Sort binary tree (binary lookup tree (English: Binary search tree), also known as binary searching trees, ordered binary tree);
      • Hoffman (For information coding): The shortest two-tree with the right path is called Huffman tree or optimal binary tree;
      • B-Tree: A self-balancing two-fork lookup tree optimized for read and write operations that keeps data in order and has two additional subtrees

two basic concepts of fork trees

A binary tree is a tree structure with a maximum of two subtrees per node. The subtree is often referred to as the left subtree and the right sub-tree (subtree)

two nature of the fork Tree (properties)

Nature 1:  there are at most 2^ (i-1) nodes (i>0) on the level I layer of the binary tree
two fork tree with a depth of K 2:  at most 2^k-1 nodes (k>0)
nature 3:  for any binary tree, if its leaf node is N0, and the total number of nodes with a degree of 2 is N2, then n0=n2+1;
property 4: The depth of a full binary tree with n nodes must be log2 (n+1)
property 5: For a complete binary tree, if numbered from top to bottom, from left to right, the node numbered I, the left child number must be 2i, and the right child number must be 2i+1; The parent's number must be I/2 (except for the root of I=1)

Class Node (object): ' Node class ' ' Def __init__ (self, elem, lchild = none, Rchild = none): Self.elem = Elem        Self.lchild = Lchild Self.rchild = Rchildclass (object): ' Tree class ' Def __init__ (self, root = None): Self.root = root def add (self, elem): "' Add node for tree ' ' ' ' ' Nodes = Node ' (elem) # If it is an empty tree, assign a value to the root node if Self.root = = None:self.root = node return else:queue = [] Queue.appen D (self.root) # Hierarchical traversal of existing nodes while queue: # The first element of a popup queue cur = queue.pop (0  If Cur.lchild is None:cur.lchild = node return elif                    Cur.rchild is None:cur.rchild = node return else: # If the left and right nodes are not empty, join the queue to continue judging queue.append (cur.lchild) queue.append (cur.rchild)

Traversal of a binary tree

The traversal of a tree is an important operation of a tree. The so-called traversal refers to the information access to all nodes in the tree, that is, each node in the tree is accessed once and only once, we call this access to all nodes (traversal). Then the two important traversal modes of the tree are depth-first traversal and breadth-first traversal, and depth precedence is generally recursive, and the breadth first is generally used in queues. Most of the algorithms that can be implemented recursively can also be implemented with stacks.

Depth-First traversal

For a binary tree, depth-first search is the node that traverses the tree as deep as possible, searching the branches of the tree as far as the tree is Depth.
There are three important methods for deep traversal. These three methods are often used to access the nodes of the tree, and they differ in the order in which each node is accessed. These three types of traversal are called First Order traversal (preorder), Middle sequence Traversal (inorder), and post-order traversal (postorder). Let's give them a detailed definition, and then take a look at their application.

      • In order traversal, we first access the root node, then recursively use the first-order traversal to access the left subtree, and recursively use the first-order traversal to access the right sub-tree
        Right subtree, left dial hand tree, root node

def preorder (self, Root): "" "    recursive implementation of First order traversal" "    if root = = None:        return    print (Root.elem)    Self.preorder (Root.lchild)    Self.preorder (Root.rchild)

      • In the middle sequence traversal , we recursively use the middle order traversal to access the left subtree, then access the root node, and then recursively use the middle order traversal to access the right subtree . Left dial hand Tree----the right subtree, root node

def inorder (self, Root): "" "    recursive implementation in sequence traversal" "    if root = = None:        return    self.inorder (root.lchild)    Print (Root.elem)    Self.inorder (Root.rchild)

      • After the sequential traversal in the post -operation Traversal, we first recursively use the post-traversal to access the Saozi right subtree, the last access to the root node root node, right subtree, left dial hand tree

def postorder (self, Root): "" "    recursive implementation of subsequent traversal" "    if root = = None:        return    self.postorder (root.lchild)    Self.postorder (root.rchild)    print (Root.elem)

Breadth-first traversal (hierarchical traversal)

From the root of the tree, from top to bottom, from left to right, traverse the entire tree node

def breadth_travel (self, Root): "" "    use queue to implement tree hierarchy traversal" "    if root = = None:        return    queue = []    Queue.append (root) while    queue:        node = queue.pop (0)        print (Node.elem)        if node.lchild! = None:            Queue.append (node.lchild)        if node.rchild! = None:            queue.append (Node.rchild)

---Study on the Road (a) Python data structures and algorithms (5) binary search, binary tree traversal

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.