Java search algorithm (4): Binary sorting tree, java binary

Source: Internet
Author: User

Java search algorithm (4): Binary sorting tree, java binary

[Why do I use the binary sorting tree?]

If the queried dataset is an ordered linear table and is stored in sequence, you can use search algorithms such as semi-segmentation and interpolation, it takes a lot of time.

Because the binary sorting tree uses the link storage method, you do not need to move elements when performing the insert or delete operation, so the insertion and deletion time performance is better.


[Features of binary sorting tree]

A binary sorting tree is also called a binary search tree. It is either an empty tree or a binary tree of the following nature:

1. If its left subtree is not empty, the values of all nodes on the left subtree are smaller than the value of its root node.

2. If its right subtree is not empty, the value of all nodes on the right subtree is greater than the value of its root node.

3. Its left and right subtree are also Binary Decision Trees.


[Implementation of binary sorting tree]

Import java. util. iterator; import java. util. noSuchElementException;/*** binary sorting tree, also known as binary search tree, has the following properties: * 1. if its left subtree is not empty, all nodes in the left subtree are smaller than its root node * 2. if its right subtree is not empty, the value of all nodes on the right subtree is greater than the root node x 3. its left/right subtree is also a binary sorting tree * For simplicity, assume that all elements in the tree have implemented the Comparable interface or they can compare */public class BinarySortTree <E >{// root node private Entry <E> root = null; // number of elements in the tree private int size = 0; public BinarySortTree () {} public int size () {return size;} public E getRoot () {Return root = null? Null: root. element;}/*** Recursive Implementation: Find whether the specified element exists in the tree. If the search fails, check whether it is added, if the search is successful, the system returns * @ param t, indicating that the parent node * @ param f saves t is searched down from this node * @ param p. if the search is successful, p points to this data element node, otherwise, return the last node */private boolean searchBST (Entry <E> t, Object element, Entry <E> f, Entry <E> p) in the search path) {if (t = null) {p = f; return false;} Comparable <? Super E> e = (Comparable <? Super E>) element; int cmp = e. compareTo (t. element); if (cmp <0) {return searchBST (t. left, element, t, p);} else if (cmp> 0) {return searchBST (t. right, element, t, p) ;}else {p = t; return true ;}/ *** non-Recursive Implementation */private boolean searchBST (Object element, entry [] p) {Comparable <? Super E> e = (Comparable <? Super E>) element; Entry <E> parent = root; Entry <E> pp = null; // Save the parent node while (parent! = Null) {int cmp = e. compareTo (parent. element); pp = parent; if (cmp <0) {parent = parent. left;} else if (cmp> 0) {parent = parent. right;} else {p [0] = parent; return true;} p [0] = pp; return false;}/*** search for the Binary Tree first, if the specified element cannot be found, insert it to the binary tree */public boolean add (E element) {Entry <E> t = root; if (t = null) {// if the root node is empty, root = new Entry <E> (element, null); size = 1; return false;} Comparable <? Super E> e = (Comparable <? Super E>) element; Entry [] p = new Entry [1]; if (! SearchBST (element, p) {// search failed, insert element Entry <E> s = new Entry <E> (element, p [0]); int cmp = e. compareTo (E) p [0]. element); if (cmp <0) {p [0]. left = s;} if (cmp> 0) {p [0]. right = s;} size ++; return true;} return false;}/*** remove a node and adjust the binary tree to implement the binary tree: * assume that the node to be deleted is p, the parent node is f, and the left node where p is f are discussed in three cases: * 1. if p is a leaf node, delete it directly * 2. if p has only one left child or one right child, delete p and set PL or PR to f's left subtree * 3. if the left and right Subtrees of p are not empty, we can see from the characteristics of the binary sorting tree that before p is deleted, traverse the binary tree in the middle order * to get an ordered sequence. After p is deleted To keep the relative positions of other elements unchanged, you can do this: * replace p with the direct precursor (or directly successor) of p, and then delete its direct precursor or direct successor. Its direct precursor can be obtained from the features of sequential traversal */public boolean remove (Object o) {Entry [] p = new Entry [1]; if (searchBST (o, p )) {deleteEntry (p [0]); // the query is successful. The deletion element return true;} return false;} private void deleteEntry (Entry <E> p) {size --; if (p. left! = Null & p. right! = Null) {// If the left and right subtree of p are not empty, locate it and replace pEntry <E> s = successor (p); p. element = s. element; p = s;} Entry <E> replacement = (p. left! = Null? P. left: p. right); if (replacement! = Null) {// if either of its left and right subtree is not empty replacement. parent = p. parent; if (p. parent = null) // if p is the root node root = replacement; else if (p = p. parent. left) // If p is left child p. parent. left = replacement; elsep. parent. right = replacement; // If p is the right child p. left = p. right = p. parent = null; // p pointer to clear} else if (p. parent = null) {// if there is only one node root = null in the entire tree;} else {// left and right subtree are empty, p is the leaf node if (p. parent! = Null) {if (p = p. parent. left) p. parent. left = null; else if (p = p. parent. right) p. parent. right = null; p. parent = null ;}}/ *** returns the result of traversing the tree in the ascending order, direct successor to t */static <E> Entry <E> successor (Entry <E> t) {if (t = null) return null; else if (t. right! = Null) {Entry <E> p = t. right; // to the right, and then left until the end while (p. left! = Null) p = p. left; return p;} else {// right is null. If t is the left subtree of p, p is the direct successor Entry of t <E> p = t. parent; Entry <E> ch = t; while (p! = Null & ch = p. right) {ch = p; // If t is the right subtree of p, continue to search for its direct successor p = p. parent;} return p ;}} public Iterator <E> itrator () {return new BinarySortIterator ();} /*** returns the Iterator for traversing the tree in the middle order */private class BinarySortIterator implements Iterator <E >{ Entry <E> next; Entry <E> lastReturned; public BinarySortIterator () {Entry <E> s = root; if (s! = Null) {while (s. left! = Null) {s = s. left; // find the first element in the middle-order traversal} next = s; // assign it to next} @ Overridepublic boolean hasNext () {return next! = Null ;}@ Overridepublic E next () {Entry <E> e = next; if (e = null) throw new NoSuchElementException (); next = successor (e ); lastReturned = e; return e. element ;}@ Overridepublic void remove () {if (lastReturned = null) throw new IllegalStateException (); // deleted entries are replaced by their successorsif (lastReturned. left! = Null & lastReturned. right! = Null) next = lastReturned; deleteEntry (lastReturned); lastReturned = null;}/*** Tree node. Do not write get for convenience, set Method */static class Entry <E> {E element; Entry <E> parent; Entry <E> left; Entry <E> right; public Entry (E element, entry <E> parent) {this. element = element; this. parent = parent;} public Entry () {}} // just for testpublic static void main (String [] args) {BinarySortTree <Integer> tree = new BinarySortTree <Integer> (); tree. add (45); tree. add (24); tree. add (53); tree. add (45); tree. add (12); tree. add (90); System. out. println (tree. remove (400); System. out. println (tree. remove (45); System. out. println ("root =" + tree. getRoot (); Iterator <Integer> it = tree. itrator (); while (it. hasNext () {System. out. println (it. next ();} System. out. println (tree. size ());}}



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.