Two Fork Lookup Tree __math

Source: Internet
Author: User
Tags comparable

Two fork Lookup tree (binary search trees, also called a binary search tree or binary sorting tree is a very important data structure, many advanced tree structure are two fork to find a variety of trees, such as AVL tree, red black tree, etc., understand the binary lookup tree for the subsequent tree structure learning has a good role. At the same time, the use of binary lookup tree can be sorted, called binary ordering, but also a very important idea.

In this paper, the main reference algorithm introduction, Detailed introduction of binary lookup tree principle and specific Python and Java code implementation. 1. Define

The lookup tree is a data structure that supports a variety of dynamic collection operations, including Search,minimum,maximum,predecessor,successor,insert and delete. It can be used either as a dictionary or as a priority queue.

Description of Wiki:

The nature of the binary tree lookup:
1. If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than the value of its root node;
2. The right subtree of any node is not empty, the value of all nodes on the right subtree is greater than the value of its root node;
3. The left and right subtree of any node is a two-fork lookup tree, respectively. There is no node with equal key values (no duplicate nodes).
4. The advantage of a two fork lookup tree over other data structures is that the time complexity of finding and inserting is low. is O (log n).

The binary lookup tree is the basic data structure, which is used to build more abstract structures such as collections, multiset, associative arrays, etc.
Although the worst efficiency of a binary lookup tree is O (n), it supports dynamic querying, and there are many improved versions of the two-fork lookup tree that can make the tree tall for O (Logn), such as SBT,AVL, red-black tree, etc. two. Python implementation

Use the two-fork tree shown below to illustrate the lookup algorithm

Node class

Create a class, named node, as a two-fork tree node structure, including: Zodi, right branch, node data three variables.

Class Node: "" "
    two fork tree left and right branch" "
    def __init__ (self, data):" ""
        Node Structure ""

        "
        self.left = None
        self.right = None
        self.data = data

For example, create a node that contains an integer 8. Because only one node is created, the left and right branches are none.

Root = Node (8)

This will get a tree with only one node as shown in the following figure.

Insert Method

Now that there is a bare tree, with twigs and leaves, you must add new nodes and data using the Insert data method.

def insert (self, data): ""
    Insert node Data ""
    if data
    < self.data:
        if Self.left is None:
            Self.left = Node (data)
        else:
            self.left.insert (data)
    elif data > Self.data:
        if Self.right is None:
            self.right = Node (data)
        else:
            self.right.insert (data)

To take the previous action, you can add the tree's branches and leaves (left and right branches and node data) in the following way.

Root.insert (3)
Root.insert (Root.insert) (
1)

When the second node is added to Data 3, the program will: the first step, root invokes Insert (), whose parameters are data=3 second step, comparing 3 and 8 (existing root nodes), 3:8 small. And the left branch of the tree is none, so a new node is created on the left.

Add third node data 10, the program will: the first step, as in the first step, but data=10 second step, found that 10 is greater than 8, while the right is none, so that it as the right new branch node data.

Add the fourth node Data 1, the program will: the first step, the former, data=1 second step, 1 is less than 8, so it should be placed on the left branch of the tree; The third step, the left branch already has the child node 3, the node calls the Insert () method again, 1 is less than 3, so 1 as the child node of 3, and placed on the left of the original none.

So, it forms the tree of the following figure

Continue to increase node data

Root.insert (6)
Root.insert (4)
Root.insert (7)
Root.insert (Root.insert) (
13)

The tree that eventually forms the following figure

Traverse Tree

This method is used to find a node in the tree and, if found, returns the node or none. For convenience, the parent node is also returned.

Def lookup (self, data, Parent=none): ""
    traversing the binary tree ""
    if data < self.data:
        if Self.left is None: Return
            None, the None return
        self.left.lookup (data, self)
    elif data > Self.data:
        if Self.right is none:< C9/>return None, none return
        self.right.lookup (data, self)
    else: return
        self, parent

Test it and look for a node with a data of 6

node, parent = Root.lookup (6)

After calling lookup (), the program does this: Call lookup (), pass the parameter data=6, default Parent=none data=6, the value of the root node 8 pointer to the left of the root node, at this point: data=6,parent=8, call lookup again () Data=6 is greater than the left first level node data 3 pointer to the right branch of 3, data=6,parent=3, call again lookup () node data equals 6, then return this node and its parent node 3

Delete Method

Deletes the node data. The code is as follows:

def delete (self, data): "" Delete Node "" "node, parent = self.lookup (data) #已有节点 if node is not None : Children_count = Node.children_count () #判断子节点数 If Children_count = 0: # If there are no child nodes under the node, you can  Delete if parent.left is node:parent.left = None Else:parent.right = None del node Elif children_count = 1: # If you have a child node, move the child node up to replace the node (which disappears) if nod
                E.left:n = Node.left Else:n = node.right If Parent: 
            If parent.left is Node:parent.left = n else:parent.right = n del node Else: # If you have two child nodes, you have to judge all the leaves under the node parent = node successor = n
            Ode.right while successor.left:parent = successor successor = Successor.left Node.data =Successor.data if Parent.left = = Successor:parent.left = Successor.right Else:
 Parent.right = Successor.right

In the above method, after the number of child nodes under the current node is obtained, needs to be judged in three cases. If there is no child node, delete directly if there is a child node, to move the next child node to the current node, that is, if there are two child nodes, you have to judge the data of your own point and sort the nodes from the new arrangement.

The method used to count the number of child nodes, the code is as follows:

def children_count (self): "" ""
    number of child nodes ""
    cnt = 0
    if self.left:
        cnt + + 1
    if self.right:
        CNT + 1 return
    CNT

Example 1: Delete the node with data 1, it is a child of 3, and 1 has no child nodes after it

Root.delete (1)

compare two binary trees

Comparing two binary tree methods, as long as there is a node (leaf) and another tree is different, it returns false, also includes the absence of the corresponding leaves.

def compare_trees (Self, Node): ""
    compare Two Trees ""
    if node is None: Return
        False
    if Self.data!= Node.data: Return
        false
    res = True
    if self.left are None:
        if Node.left: return
            false
    else:
        res = self.left.compare_trees (node.left)
    if is false: return
        false
    if Self.right is None:
        if Node.right: return
            False
    else:
        res = self.right.compare_trees (node.right) return
    Res

For example, compare tree (3,8,10) and tree (3,8,11)

Root2 is the root of tree (3,8,11), Root of tree (
3,8,10)
root.compare_trees (ROOT2)

Execute the above code, the program will go this way: root called Compare_trees () method Root has the left child node, call the node compare_trees () Two left child node comparison, return True follow the previous procedure, compare the right node, found that different, Returns false

Print Tree

Print out the two-fork tree in a certain order. No arguments are required. The practice is to first left and right (left less than right).

def print_tree (self): ""
    print number of items in order ""
    if Self.left:
        self.left.print_tree ()
    Print Self.data,
    if self.right:
        self.right.print_tree ()

To operate:

Root.print_tree ()

Output: 1, 3, 4, 6, 7, 8, 10, 13, 14

the builder that contains all the tree elements

It is sometimes necessary to create a generator that contains all the tree elements. Given the memory problem, it is not necessary to generate all the node data lists in real time, but rather to return the value of the next node each time this method is called. To do this, use it to return an object and stop there, and the function will continue to return the value from there by the yield keyword the next time the method is called. In this case, to use the stack, you cannot use recursion.

def tree_data (self): "" "" ""
    two fork tree data Structure ""
    stack = []
    node = self while
    stack or node: 
        if Node:
            stack.append (node)
            node = node.left
        Else: 
            node = stack.pop ()
            yield node.data
            node = Node.right

For example, the tree is obtained by looping:

For data in Root.tree_data ():
    print Data

The program takes the data into the stack, out of the stack, in sequence, and returns the result, according to the Atom on the left and right. three. Java implementation insert Operation

Binary tree Find tree B insert operation x is as follows:

1. If b is an empty tree, insert the node directly as the root node.
2, x equals b The value of the data of the root node, then return directly, otherwise.
3. If x is less than the value of the data of the root node of B, change the position of the node that X is to insert to the left subtree of B, otherwise. 4. Change the position of the x to the right subtree of B.

/** Insert Element */public
   void Insert (T t)
   {
       roottree = insert (t, roottree)
   ;
/** at a certain location to start judging insert element
   /public binarynode<t> Insert (T t,binarynode<t> node)
   {
       if (node==null)
       {
           ///New construct a binary lookup tree return
           new binarynode<t> (T, NULL, NULL);
       }
       int result = T.compareto (node.data);
       if (result<0)
          node.left= Insert (t,node.left);
       else if (result>0)
          node.right= Insert (t,node.right);
       else
           ;//donothing return
       node;
   }
Find Operations

The process of looking for x in a binary lookup tree is as follows:

1, if the binary tree is empty tree, then find failure.
2, if x equals the data of the root node, then find success, otherwise.
3, if X small root node data, then recursively find its left subtree, otherwise.
4, recursively find its right subtree.

According to the above steps, write out the code for its lookup operation.

/** find the specified element, default from the * root node out of the start query/public boolean contains (T-t) {return contains (T, Roottree); /** start lookup element from a node/public boolean contains (T T, binarynode<t> node) {if (node==null) return FA
       lse;//node is empty, lookup failed int result = T.compareto (node.data); if (result>0) return contains (t,node.right);//recursive query right subtree else if (result<0) return contains (T,
   Node.left);//recursive query left subtree else return true;
      /** Here I provide a search for the maximum minimum value of a two-fork tree * */** Find the minimum value in the two Fork lookup tree/Public T findmin () {if (IsEmpty ())
          {System.out.println ("Two fork Tree is empty");
      return null;

   }else return Findmin (roottree). data; /** found the maximum value in the two-fork lookup tree/Public T Findmax () {if (IsEmpty ()) {System.out.println ("Two-fork tree is empty
              ");
          return null;
   }else return Findmax (roottree). data; /** query for the node where the smallest element is located/public binarynode<t> Findmin (binarynoDe<t> node) {if (node==null) return null;
       else if (node.left==null) return node; 
   Return Findmin (Node.left);//Recursive lookup}/** query the node where the maximum element is located * * Public binarynode<t> Findmax (binarynode<t> node)
       {if (node!=null) {while (node.right!=null) node=node.right;       
   } return node; }
Classical binary tree lookup algorithm

Two-fork tree algorithm code with no bugs for personal use:

int BinarySearch (int array[], int n, int value)
{
    int left = 0;
    int right = n-1;
    If this is the int right = N, then there are two places that need to be modified to ensure that one by one corresponds to:
    //1, the following loop condition is while (left < right)
    //2, within the loop when Array[middle] >  Value, right = Mid

    whilst (left <= right)  //loop condition, timely and variable
    {
        int middle = left + (right-left) >> 1);  Prevent overflow, displacement is also more efficient. At the same time, each cycle needs to be updated.

        if (Array[middle] > value)
        {Right
            = middle-1;  Right assignment, timely and variable
        }
        else if (Array[middle] < value)
        {left
            = middle + 1;
        }
        else return
            middle;
        There may be a reader who thinks it's the first to judge the equality, but after all, the inequality in the array is more
        //If each loop is judged to be equal, it will take time
    }
    return-1.

Two-fork Tree lookup algorithm in JDK:

    /**
     *
     * @Title: JDK arrays Two-fork tree Lookup Implementation code
     * @Description: Find key in array A and return to its position
     * @date: 2016/6/22 19:16
     * @param
     * @return//Like public
    version, but without range checks.
    private static int BinarySearch0 (object[] A, int fromindex, int toindex,
                                     Object key) {
        int low = fromindex;
  
   int high = toIndex-1;

        While [low <= high] {
            int mid = (low + high) >>> 1;
            @SuppressWarnings ("Rawtypes")
            comparable midval = (comparable) a[mid];
            @SuppressWarnings ("unchecked")
            int cmp = Midval.compareto (key);

            if (CMP < 0) Low
                = mid + 1;
            else if (CMP > 0) High
                = Mid-1;
            else return
                mid;//key found
        } return
        -(low + 1);  Key not found.
    }
  

The detailed implementation code for Java and Python is shown in my GitHub.

Reference article: http://www.laurentluce.com/posts/binary-search-tree-library-in-python/comment-page-1/

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.