Binary Search Tree

Source: Internet
Author: User

Binary Search Tree
The following figure shows two binary search trees. We can summarize their features: (1) if its left subtree is not empty, then the value of all the nodes on the left Tree is 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 Search Tree 1. We traverse these two trees in order to find an ordered data sequence: [1 2 3 4 5 6 7 8] insert operation of the Binary Search Tree: now we want to find a number 9. If it does not exist, add it to the diagram. Let's take a look at the process of dynamically adding a binary search tree: 1). When number 9 is compared with root node 4 (9> 4), 9 is placed in the right subtree of node 4. 2). Then, if 9 is compared with node 5 (9> 5), 9 is placed in the right subtree of node 5. 3). Similarly, until 9 is compared with node 8 (9> 8), 9 is placed in the right subtree of node 8 and becomes the right child of node 8. In this process, we can find that dynamic addition of any data will be added to the leaf node of the original tree structure without building a new one. It can be seen that the dynamic search structure has a huge advantage in this respect. Delete operation: If the left and right subtree of the node to be deleted exist in the binary search tree, you need to change the child tree structure when deleting the node, but the cost is very small. The Efficiency Analysis of the Binary Search Tree clearly shows that finding a data in the binary search tree of a and B does not need to traverse all the node elements, and the search efficiency is indeed improved. However, there is a very serious problem: we need to compare data 5 times in Figure A, but only 3 times in Figure B. More seriously: If a binary search tree is created in an ordered sequence [1 2 3 4 5 6 7 8, the entire tree degrades to a linear structure (for example, the c input graph: single decision tree). In this case, we need to compare 8 data records, which is no different from sequential search. To sum up, in the worst case, the binary sorting tree is transformed into a single tree with a depth of n. the time complexity of searching is the same as that of sequential searching ). The best case is that the shape of the binary sorting tree is the same as that of the semi-query decision tree, and its average search length is proportional to log2 (N) (O (log2 (n ))). This indicates that the structure of the search tree is completely different for the same set of data, which directly affects the search efficiency. Code copy code/*** Binary Tree node Structure */class BSTNode <E extends Comparable <E> {/** node keyword */E key = null; /** direct parent node */BSTNode <E> parent = null;/** root node of the Left subtree of the node */BSTNode <E> lchild = null; /** root node of the right subtree of the node */BSTNode <E> rchild = null; BSTNode (E k) {this. key = k ;}/ *** Binary Search Tree (BST) */public class BST <E extends Comparable <E >{/ ** root */private BSTNode <E> root = null; public BST () {}/*** BST query keyword * @ param key off Key word * @ return query succeeded/true, query failed/false */public boolean search (E key) {System. out. print ("Search Keyword [" + key + "]:"); if (key = null | root = null) {System. out. println ("search failed"); return false;} else {System. out. print ("search path ["); if (searchBST (root, key) = null) {return false;} else return true ;}} /*** BST insert keyword * @ param key keyword * @ return insert successful/true, insert failed/false */public boolean insert (E key) {System. out. print ("insert keyword [" + Key + "]:"); if (key = null) return false; if (root = null) {System. out. println ("insert to the root. "); Root = new BSTNode <E> (key); return true;} else {System. out. print ("search path ["); return insertBST (root, key) ;}} public boolean delete (E key) {System. out. print ("delete keyword [" + key + "]:"); if (key = null | root = null) {System. out. println ("failed to delete"); return false;} else {System. out. print ("search path ["); // locate the node BSTNode to be deleted in the tree <E> nodeDel = searchBST (root, key); if (nodeDel = null) {return false;} The right subtree of else {// nodeDel is empty. You only need to re-connect the left subtree Subtree if (nodeDel. rchild = null) {BSTNode <E> parent = nodeDel. parent; if (parent. lchild. key. compareTo (nodeDel. key) = 0) parent. lchild = nodeDel. lchild; else parent. rchild = nodeDel. lchild;} // if the left subtree is empty, the right subtree else if (nodeDel. lchild = null) {BSTNode <E> parent = nodeDel. parent; if (parent. lchild. key. compareTo (nodeDel. key) = 0) parent. lchild = nodeDel. rchild; else parent. rchild = nodeDel. rchild;} // The left and right subtree are not empty. else {BSTNode <E> Q = nodeDel; // first find the left node s BSTNode of nodeDel <E> s = nodeDel. lchild; // then locate to the right end of s (this node replaces nodeDel), where q is always located at s's direct parent node while (s. rchild! = Null) {q = s; s = s. rchild;} // Replace the node del keyword with the node del keyword "s. key = s. key; // reset the left subtree if (q! = NodeDel) q. rchild = s. lchild; else q. lchild = s. lchild;} return true;}/*** recursive search key sub-node * @ param node tree node * @ param key keyword * @ return: the node is returned, otherwise, null is returned. */Private BSTNode <E> searchBST (BSTNode <E> node, E key) {if (node = null) {System. out. println ("]. search failed "); return null;} System. out. print (node. key + "->"); // The keyword if (node. key. compareTo (key) = 0) {System. out. println ("]. search successful "); return node;} // search else if (node. key. compareTo (key)> 0) {return searchBST (node. lchild, key);} // search else {return searchBST (node. rchild, key) ;}}/*** recursive insert keyword * @ param n Ode Tree node * @ param key tree keyword * @ return true/Insert successful, false/Insert failed */private boolean insertBST (BSTNode <E> node, E key) {System. out. print (node. key + "->"); // find the same keyword in the original tree, no need to insert. If (node. key. compareTo (key) = 0) {System. out. println ("]. search with the same keyword, insertion failed "); return false;} else {// search for the left subtree of node if (node. key. compareTo (key)> 0) {// if the left subtree of the current node is empty, insert the key node of the new node to the left child if (node. lchild = null) {System. out. println ("]. insert to "+ node. key + "left child"); BSTNode <E> newNode = new BSTNode <E> (key); node. lchild = newNode; newNode. parent = node; return true;} // If the left subtree of the current node exists, the left subtree else return insertBST (node. lch Ild, key);} // search for the right subtree else of node {if (node. rchild = null) {System. out. println ("]. insert to "+ node. key + "right child"); BSTNode <E> newNode = new BSTNode <E> (key); node. rchild = newNode; newNode. parent = node; return true;} else return insertBST (node. rchild, key) ;}}/ *** get the BST root node * @ return BST root node f */public BSTNode <E> getRoot () {return this. root;}/*** recursively traverse BST */public void InOrderTraverse () {if (root = null) retur N; BSTNode <E> node = root; ArrayList <BSTNode <E> stack = new ArrayList <BSTNode <E> (); stack. add (node); while (! Stack. isEmpty () {while (node. lchild! = Null) {node = node. lchild; stack. add (node) ;}if (! Stack. isEmpty () {BSTNode <E> topNode = stack. get (stack. size ()-1); System. out. print (topNode. key + ""); stack. remove (stack. size ()-1); if (topNode. rchild! = Null) {node = topNode. rchild; stack. add (node) ;}}}/*** test */public static void main (String [] args) {BST <Integer> tree = new BST <Integer> (); tree. insert (new Integer (100); tree. insert (new Integer (52); tree. insert (new Integer (166); tree. insert (new Integer (74); tree. insert (new Integer (11); tree. insert (new Integer (13); tree. insert (new Integer (66); tree. insert (new Integer (121); tree. search (new Integer (11); tree. inOrderTraverse (); tree. delete (new Integer (11); tree. inOrderTraverse ();}}

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.