Relive data structure: Two-fork sort tree Find, insert, delete

Source: Internet
Author: User

After reading this article you will learn:

      • What is a two fork sort tree binary sort trees BST
      • The key operation of binary sort tree
        • Find
        • Insert
        • Delete
      • Run a code test
      • A question of a face
      • Summarize
      • Thanks

We know that binary lookups can shorten the time to find, but one requirement is that the data being looked up must be orderly . To maintain an ordered set of data for each search and operation, the concept of a two-fork sort tree is maintained.

In the previous article we introduced the concept of two-fork tree, the binary tree has the left and right sub-tree, presumably in the distinction between the two sub-tree has certain rules.

Now let's introduce a special form of binary tree-two-fork sort tree to understand its distinguishing strategy and common operation.

What is a two-fork sort tree binary sort trees, BST

Binary sorting tree, also known as binary search tree, binary searching tree, B-tree.

A binary sort tree is a two-fork tree with the following properties:

    • If the left subtree is not empty, the value of all nodes on the left subtree is less than the value of its root node;
    • If the right subtree is not empty, the value of all nodes on the right subtree is greater than or equal to the value of its root node;
    • The left and right sub-trees are also two-fork sorting trees respectively.

In other words, the binary sort tree, the left subtree is smaller than the node, the right subtree is larger than the node, recursive definition.

According to the characteristics of binary sorting tree, we can know that the middle sequence traversal of binary sort tree must be small to large, for example, the middle sequence traversal result is:

1 3 4 6 7 8 10 13 14

Key operations for binary sort trees 1. Find

Based on the definition of a binary sort tree, we can know when looking for an element:

    • Compare it to the root node, return the equality, or the root node is empty, indicating that the tree is empty, also return;
    • If it is smaller than the root node, it is searched recursively from the Shari of the root;
    • If it is larger than the root node, it is searched recursively from the right subtree of the root.

As you can see, this is a two-point lookup .

Code implementation:

public class BinarySearchTree {    private BinaryTreeNode mRoot;   //根节点    public BinarySearchTree(BinaryTreeNode root) {        mRoot = root;    }    /**     * 在整个树中查找某个数据     *     * @param data     * @return     */    public BinaryTreeNode search(int data) {        return search(mRoot, data);    }    /**     * 在指定二叉排序树中查找数据     *     * @param node     * @param data     * @return     */    public BinaryTreeNode search(BinaryTreeNode node, int data) {        if (node == null || node.getData() == data) {    //节点为空或者相等,直接返回该节点            return node;        }        if (data < node.getData()) {    //比节点小,就从左子树里递归查找            return search(node.getLeftChild(), data);        } else {        //否则从右子树            return search(node.getRightChild(), data);        }    }}

As you can see, finding in a binary sort tree is very simple, but it relies on maintaining the entire sort tree structure each time you insert or delete an element.

2. Insert

The insertion in a binary tree is divided into two main steps: Find, insert:

    • First look for the entire element, some words do not have to insert, direct return;
    • No right place to find (contrast) before inserting into.

In addition to setting the data when inserting, but also need to bind with the parent node, let the parent node aware of your child: smaller than the parent node is the left child, the big is the right child.

Code implementation:

/** * inserted into the entire tree * * @param data */public void Insert (int data) {if (mroot = = null) {///If the current is an empty tree, create a new Mroot = n        EW Binarytreenode ();        Mroot.setdata (data);    Return     } searchandinsert (null, mroot, data); Father of the root node for null}/** * Two-step walk: Find, Insert * * @param parent to bind to node * @param node Current compare nodes * @param data */private Binarytreenod E Searchandinsert (binarytreenode Parent, binarytreenode node, int data) {if (node = = null) {///The current comparison node is empty, stating that the data was not previously        Add new, insert node = new Binarytreenode ();        Node.setdata (data); if (parent! = NULL) {//parent node is not empty, bind relationship if (Data < Parent.getdata ()) {Parent.setleftchild (nod            e);            } else {parent.setrightchild (node);    }} return node;    }//The node in the comparison is not empty if (node.getdata () = = data) {//already has, without inserting the return node;  The else if (Data < Node.getdata ()) {//is smaller than the node, finds from the left subtree, inserts a return Searchandinsert (node, node.getleftchild (), data);   } else {return Searchandinsert (node, node.getrightchild (), data); }}
3. Delete *

Insert operations are similar to lookups, while deletions are relatively complex and need to be treated according to the condition of the deleted nodes:

    • If the node to be deleted is just a leaf node, it is Ok to delete it directly;
    • If the node you want to delete has child nodes, you need to establish a relationship between the parent and child nodes:
      • If there is only a left child or right child, just move the child up and down to the location to be removed;
      • If you have two children, you need to choose the right child node as the new root node, the node is called an inheritance node .

The new node requirement is larger than all the left subtree, smaller than all right subtree, how to choose?

* * More than the value of all the left subtree, the right sub-tree small, from the right subtree to find the smallest good;
You can also find the largest from the left subtree. **

Both options are available, this article selects the smallest node in the right subtree, which is the leftmost node in the right sub-tree.

Code implementation:

/** * Find the parent node of the specified data node in the entire tree * * @param data * @return */public binarytreenode searchparent (int data) {return Searchparen T (null, mroot, data);} /** * Find the parent node of the specified data node under the specified node * * @param parents of the current comparison node * @param node currently being compared to nodes * @param data lookup @return */public B        Inarytreenode Searchparent (binarytreenode Parent, binarytreenode node, int data) {if (node = = null) {///comparison of the node is empty return null    return null;    if (node.getdata () = = data) {//found the target node, return the parent node returned to parent;    The else if (Data < Node.getdata ()) {//is smaller than the current node, record recursively finds the return Searchparent (node, node.getleftchild (), data);    } else {return searchparent (node, node.getrightchild (), data); }}/** * Delete the specified data node * * @param data */public void Delete (int data) {if (Mroot = = NULL | | mroot.getdata () = = data) {//root        The node is empty or the root node is deleted, and the Mroot = null is dropped directly;    Return    }//The father Binarytreenode parent = searchparent (data) to be found before deleting it; if (parent = = NULL) {//If the parent node is empty, the tree is empty and the re cannot be deletedTurn    The next step is to find the node to be deleted Binarytreenode Deletenode = search (parent, data);    if (Deletenode = = null) {//tree cannot find the node to delete return; }//Delete node There are 4 cases of//1. The left and right subtrees are empty, indicating that the leaf node is deleted, directly deleting if (deletenode.getleftchild () = = NULL && Deletenode.getrightchil        D () = null) {//delete node deletenode = null;            Reset the child state of the parent node and tell him you don't have the son. if (parent.getleftchild () = null && parent.getleftchild (). GetData () = = data) {        Parent.setleftchild (NULL);        } else {parent.setrightchild (null);    } return; } else if (deletenode.getleftchild () = null && deletenode.getrightchild () = = null) {//2. The node to be deleted is only the left dial hand tree, and the left subtree Bearing position if (parent.getleftchild () = null && parent.getleftchild (). GetData () = = data) {Parent.setle        Ftchild (Deletenode.getleftchild ());        } else {Parent.setrightchild (Deletenode.getleftchild ());        } deletenode = null;    Return } else if (DeleteNoDe.getrightchild ()! = null && deletenode.getrightchild () = = null) {//3. The node to be deleted is only the right subtree, and the right subtree inherits the position if (par Ent.getleftchild ()! = null && parent.getleftchild (). GetData () = = data) {Parent.setleftchild (deletenode        . Getrightchild ());        } else {Parent.setrightchild (Deletenode.getrightchild ());    } deletenode = null;   } else {//4. Node to be deleted children, both Zuozi and have right sub-tree, need to choose a suitable node inheritance, here using the right subtree of the left node binarytreenode copyofdeletenode = Deletenode; To delete a copy of a node, point to the parent node of the inherited node Binarytreenode Heresnode = Deletenode.getrightchild (); To inherit the node of the location, initially the tree root//right subtree of the right subtree to delete the node has no left child, he is the smallest, direct upper if (heresnode.getleftchild () = = null) {//upper,        Brother became a child Heresnode.setleftchild (Deletenode.getleftchild ()); } else {//right subtree has left child, Loop finds the leftmost, that is, the smallest while (heresnode.getleftchild ()! = null) {Copyofdele       Tenode = Heresnode; Copyofdeletenode points to the parent node of the inherited node Heresnode = heresnode.gEtleftchild ();            }//found an inheritance node, the right subtree of the inherited node (if any) to move up one copyofdeletenode.setleftchild (Heresnode.getrightchild ());            Inheriting nodes inherit the family's family first, turn their left and right child into the child Heresnode.setleftchild (Deletenode.getleftchild ()) to delete the node;        Heresnode.setrightchild (Deletenode.getrightchild ());  }//Finally, confirm the location and let the parent node of the node to be removed recognize the new son if (parent.getleftchild () = null && parent.getleftchild (). GetData () = =        Data) {Parent.setleftchild (Heresnode);        } else {parent.setrightchild (heresnode); }    }}
Run a code test

As can be seen, binary sorting tree to find, add simple, delete logic is more, we think example:

Test code:

@Testpublic void delete() throws Exception {    //乱序插入到二叉排序树中    BinarySearchTree binarySearchTree = new BinarySearchTree(null);    binarySearchTree.insert(8);    binarySearchTree.insert(3);    binarySearchTree.insert(1);    binarySearchTree.insert(6);    binarySearchTree.insert(4);    binarySearchTree.insert(7);    binarySearchTree.insert(10);    binarySearchTree.insert(13);    binarySearchTree.insert(14);    //中序遍历    binarySearchTree.iterateMediumOrder(binarySearchTree.getRoot());    System.out.println("");    //查找某个数据    System.out.println(binarySearchTree.search(10).getData());    //删除某个数据对应的元素    binarySearchTree.delete(6);    //中序遍历删除后的二叉排序树    binarySearchTree.iterateMediumOrder(binarySearchTree.getRoot());}

Operation Result:

A question of a face

Enter a two-dollar lookup tree to convert the two-dollar lookup tree into a sorted doubly linked list. Requires that no new nodes be created, only the pointer is adjusted. For example, the two-dollar lookup tree:

                                        10                                      /                                        6       14                                  /  \     /                                 4     8  12    16

Converted to a doubly linked list: 4=6=8=10=12=14=16

Analytical:
This is said to be Microsoft's face test, at first glance seems to be very troublesome, but also binary sorting tree is a two-way chain list, in fact, the investigation is very basic things, discerning eye a look on the tree will be found as long as the sequence is the two Fork tree node sort (otherwise it is called binary sorting tree ...) ), then we simply traverse through the tree, traverse to a node and point the left pointer of the node to the last traversed node, and point the right pointer of the last traversed node to the node that is now traversing, so when we traverse the complete tree, our doubly linked list is changed! This allows you to neither add redundant nodes nor add extra pointer variables.

The problem turns from: http://blog.renren.com/share/249404913/6219142584

You can write down the code and try it.

Summarize

The performance of a binary sort tree depends on the number of layers of the two fork tree:

    • The best case is O (LOGN), which exists in the case of a fully binary sort tree, and its access performance is approximate to binary lookup;
    • The worst time is O (n), such as the inserted element is ordered, the resulting two-fork sorting tree is a linked list, in which case, it is necessary to traverse all the elements (see B).

Thanks

Ease of learning algorithm

http://blog.csdn.net/v_JULY_v/article/details/6530142/
http://blog.csdn.net/v_july_v/article/details/6543438

Http://baike.baidu.com/link?url= Ggnlvdkdsifg9rinw2i9pc-h26vonbo4yoh0wicggzbovb540ebqf2-5ho1sx2imsckufu8weifjtrnl0mu648kvijhhaifiox5ckgktdprnhiaj5lq0cfhwo E-cwraf-siqjzhzdaysqgighfsga_

Relive data structure: Two-fork sort tree Find, insert, delete

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.