Java implementation of binary search tree

Source: Internet
Author: User

In order to overcome the fear of tree structure programming, it is determined to implement the binary search tree in order to master some techniques and methods of tree structure programming. Here are the basic ideas:

[1] about containers and encapsulation. Encapsulation is a very important system design idea, whether it is process-oriented function or object-oriented object, it is a technical means to implement abstraction and encapsulation. To make your system more secure and maintainable, you should keep your packaging ideas in mind. Containers are a great example of encapsulating ideas. The user's impression of the container should be succinctly expressed as: A. Can deposit the specified things; B. You can take out what you expect. And as to what is in this container, the possession of the Viper or gold, are not visible to the user. A binary lookup tree is one such container. In object-oriented programming, in order to implement tree structure, it is natural to model the tree node object. The inner class is used, and the external class models the two-fork lookup tree, and the tree node is implemented as an inner class.

[2] The program as far as possible to achieve a more practical two-fork search tree, including dynamic insertion, deletion, query the given keyword, the minimum keyword, the largest keyword; get binary tree sequence list (for sorting), etc. Because I want to be able to use this container in the future, not just programming exercises. Most algorithms for binary search tree operations refer to the 12th chapter of "Introduction to Algorithms 2", which is slightly awkward to delete. There are errors in the procedure, please note.

[3] The program is as follows:

       

/** * @author shuqin1984 2011-3-13 * * This program implements a binary search tree function, can be dynamically inserted, delete keywords; * Query given keyword, minimum keyword, maximum keyword; convert to ordered list (for sorting) * * */packa GE Datastructure.tree;import java.util.arraylist;import java.util.list;public class Binarysearchtree {//Tree root node private TreeNode root = null;//traversal node List private list<treenode> nodelist = new arraylist<treenode> ();p Rivate class TreeN Ode {private int key;private TreeNode leftchild;private TreeNode rightchild;private TreeNode parent;public TreeNode (int k  EY, TreeNode leftchild, TreeNode rightchild, TreeNode parent) {This.key = Key;this.leftchild = Leftchild;this.rightchild = Rightchild;this.parent = parent;} public int GetKey () {return key;} Public String toString () {String Leftkey = (Leftchild = = null?)  "": string.valueof (Leftchild.key)); String Rightkey = (Rightchild = = null?) "": string.valueof (Rightchild.key)); Return "(" + Leftkey + "," + Key + "," + Rightkey + ")";}}  /** * IsEmpty: Determines if the binary lookup tree is empty, returns true if NULL, otherwise false. * */public Boolean isEmpty () {if (root = = null) {return true;} else {return false;}} /** * Treeempty: For some binary lookup tree operations (such as deleting keywords), an exception is thrown if the tree is empty. */public void Treeempty () throws Exception {if (IsEmpty ()) {throw new Exception ("Tree is empty!");}}  /** * Search: Query the given keyword in the binary lookup tree * @param key given keyword * @return match the tree node of the given keyword */public TreeNode search (int key) {TreeNode Pnode = Root;while (Pnode! = NULL && Pnode.key! = key) {if (Key < Pnode.key) {pnode = Pnode.leftchild;} else {pnode = Pnode.rightchild;}} return pnode;} /** * Minelemnode: Gets the minimum keyword node in the binary lookup tree * @return The minimum key node of the binary lookup tree * @throws Exception if the tree is empty, an exception is thrown */public TreeNode Minelemnode (T Reenode node) throws exception{if (node = = null) {throw new Exception ("The Tree is empty! ");} TreeNode Pnode = Node;while (pnode.leftchild! = null) {Pnode = Pnode.leftchild;} return pnode;} /** * Maxelemnode: Gets the maximum keyword node in the binary lookup tree * @return The maximum key node of the binary lookup tree * @throws Exception if the tree is empty, an exception is thrown */public TreeNode Maxelemnode (T Reenode node) throws Exception {if (node = = null) {throw new Exception ("The Tree is empty! ");} TreeNode Pnode = Node;while (pnode.Rightchild = null) {Pnode = Pnode.rightchild;} return pnode;} /** * Successor: Gets the successor of the given node in the sequence traversal order * @param node in a given tree @return if the node has a successor node in the sequence traversal order, it returns its successor node; otherwise null * @throws EXCEP tion */public TreeNode Successor (TreeNode node) throws exception{if (node = = null) {return null;} If the right subtree of the node is not empty, then its successor is the smallest key node in the right subtree if (node.rightchild! = null) {return minelemnode (node.rightchild);} If this node right subtree is empty treenode ParentNode = Node.parent;while (parentnode! = NULL && node = = parentnode.rightchild) {node = Parentnode;parentnode = parentnode.parent;} return parentnode;} /** * Precessor: Gets the forward node of the given node in the sequence traversal order * @param node in a given tree @return if the node has a forward node in the sequence traversal order, it returns its forward node; otherwise null * @throws EXCEP tion */public TreeNode precessor (TreeNode node) throws exception{if (node = = null) {return null;} If the left subtree of the node is not empty, then its forward node is the maximum keyword node in the left Dial hand tree if (node.leftchild! = null) {return maxelemnode (node.leftchild);} If the node left subtree is empty treenode ParentNode = Node.parent;while (parentnode! = NULL && node = = Parentnode.leftchild) {node = Parentnode;parentnode = Parentnode.parent;} return parentnode;} /** * Insert: Inserts the given keyword into the two-fork lookup tree * @param key given keyword */public void insert (int key) {TreeNode parentnode = null; TreeNode NewNode = new TreeNode (key, NULL, null,null); TreeNode Pnode = root;if (root = null) {root = Newnode;return;} while (pnode! = null) {parentnode = Pnode;if (Key < Pnode.key) {pnode = Pnode.leftchild;} else if (key > Pnode.key) {pnode = Pnode.rightchild;} else {//the node already exists in the tree that matches the given keyword, then do nothing directly return return;}} if (Key < Parentnode.key) {parentnode.leftchild = Newnode;newnode.parent = parentnode;} else {parentnode.rightchild = Newnode;newnode.parent = ParentNode;}} /** * Insert: Removes the corresponding tree node matching the given keyword from the two-fork lookup tree * @param key given keyword */public void delete (int key) throws Exception{treenode Pnode = SE Arch (key), if (Pnode = = null) {throw new Exception ("There is no keyword in the tree to delete!"); Delete (pnode);} /** * Delete: Removes the given node from the two-fork lookup tree. * @param pnode the node to delete * Pre-condition: The given node already exists in the binary lookup tree * @throws Exception */private void Delete (TreenoDe Pnode) throws Exception {if (Pnode = = null) {return; if (Pnode.leftchild = = NULL && Pnode.rightchild = = null) {//The node has no left child node, no right child node TreeNode parentnode = pnode.p.  arent;  if (Pnode = = parentnode.leftchild) {parentnode.leftchild = null;  } else {parentnode.rightchild = null;  } return; if (Pnode.leftchild = = NULL && pnode.rightchild! = null) {//The node left child node is empty, right child node non-empty TreeNode parentnode = PNODE.P  arent;  if (Pnode = = parentnode.leftchild) {parentnode.leftchild = Pnode.rightchild;  PNode.rightChild.parent = parentnode;  } else {parentnode.rightchild = Pnode.rightchild;  PNode.rightChild.parent = parentnode;  } return; } if (Pnode.leftchild! = null && Pnode.rightchild = = null) {//The node left child node is not empty, right child node is empty TreeNode parentnode = PNODE.P  arent;  if (Pnode = = parentnode.leftchild) {parentnode.leftchild = Pnode.leftchild;  PNode.rightChild.parent = parentnode;  } else {parentnode.rightchild = Pnode.leftchild; PNode.rightChild.parent = PareNtnode;  } return;  }//The node is not empty, then delete the node's successor, and replace the node TreeNode Successornode = successor (Pnode) with the subsequent node.  Delete (Successornode); Pnode.key = Successornode.key;} /** * Inordertraverselist: Get a two-fork lookup tree in the middle Sequence traversal node list * @return Binary lookup tree in the middle Sequence Traversal node list */public list<treenode> inordertraverselist ( ) {if (nodelist! = null) {nodelist.clear ();} Inordertraverse (root); return nodelist;} /** * Inordertraverse: Sequential traversal of a given binary lookup tree * @param root of a given binary lookup tree, */private void Inordertraverse (TreeNode root) {if (Root! = NULL) {inordertraverse (root.leftchild); Nodelist.add (root); Inordertraverse (Root.rightchild);}} /** * Tostringoforderlist: Get an ordered list of keywords in a binary lookup tree * @return The ordered list of keywords in the binary lookup tree */public String tostringoforderlist () { StringBuilder Sbbuilder = new StringBuilder ("["); for (TreeNode p:inordertraverselist ()) {sbbuilder.append (P.key); Sbbuilder.append ("");} Sbbuilder.append ("]"); return sbbuilder.tostring ();} /** * Gets the string representation of the two-fork lookup tree */public string, toString () {StringBuilder sbbuilder = new StringBuilder ("["); for (TreeNode p:inOrdertraverselist ()) {sbbuilder.append (P); Sbbuilder.append ("");} Sbbuilder.append ("]"); return sbbuilder.tostring ();} Public TreeNode Getroot () {return root;} public static void Testnode (Binarysearchtree BST, TreeNode pnode) throws Exception {System.out.println ("This node:" + Pnode);    SYSTEM.OUT.PRINTLN ("Anterior node:" + bst.precessor (pnode)); SYSTEM.OUT.PRINTLN ("Successor node:" + bst.successor (Pnode));}    public static void Testtraverse (Binarysearchtree BST) {System.out.println ("Binary Tree Traversal:" + BST);    SYSTEM.OUT.PRINTLN ("binary lookup tree converted to ordered list:" + bst.tostringoforderlist ());}    public static void Main (string[] args) {try {binarysearchtree BST = new Binarysearchtree (); System.out.println ("Is the lookup tree empty? "+ (Bst.isempty ()?"    Yes: "no"));    Int[] keys = new int[] {15, 6, 18, 3, 7, 13, 20, 2, 9, 4};    for (int key:keys) {Bst.insert (key); } System.out.println ("Is the lookup tree empty? "+ (Bst.isempty ()?"        Yes: "no"));    TreeNode Minkeynode = Bst.minelemnode (Bst.getroot ()); SYSTEM.OUT.PRINTLN ("Minimum keyword:" + minkeynoDe.getkey ());        Testnode (BST, Minkeynode);    TreeNode Maxkeynode = Bst.maxelemnode (Bst.getroot ());    SYSTEM.OUT.PRINTLN ("Max keyword:" + maxkeynode.getkey ());        Testnode (BST, Maxkeynode);    SYSTEM.OUT.PRINTLN ("root node Keyword:" + bst.getroot (). GetKey ());    Testnode (BST, Bst.getroot ());        Testtraverse (BST);        System.out.println ("******************************"); System.out.println ("Find 7:" + (Bst.search (7)! = null? ")    Find success! ":" Lookup failed, the keyword does not exist! ");    Bst.delete (7); System.out.println ("Find 7:" + (Bst.search (7)! = null? ")    Find success! ":" Lookup failed, the keyword does not exist! "); System.out.println ("Look Up:" + (bst.search)! = null? "    Find success! ":" Lookup failed, the keyword does not exist! ");    Bst.insert (12); System.out.println ("Look Up:" + (bst.search)! = null? "        Find success! ":" Lookup failed, the keyword does not exist! ");        Testtraverse (BST);        System.out.println ("******************************");    Bst.insert (16);    Bst.delete (6);        Bst.delete (4);        Testtraverse (BST); } catch (Exception e) {System.out.println (e.getMessage ());    E.printstacktrace (); }}} 

  

Java implementation of binary search tree

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.