Java implementation two Tree search tree

Source: Internet
Author: User

Binary tree (binary) is a special kind of tree. A binary tree can have up to 2 child nodes per node:

Two-fork Tree

Because the number of sub-nodes of the binary tree is determined, it can be implemented in memory directly by the way. Each node has a left children and a right child node (starboard children). The left Dial hand node is the root node of the Zuozi, and the right child node is the root node of the right subtree.

If we add an extra condition to the binary tree, we can get a special binary tree called the binary search tree. Binary search Tree Requirements: Each node is not smaller than any element of its left subtree, and is no larger than any element of its right sub-tree.

(If we assume that there are no duplicate elements in the tree, the above requirements can be written as follows: Each node is larger than any node in its left subtree and smaller than any node in its right subtree)

Binary search tree, notice the size of the elements in the tree

Binary search tree can easily implement the search algorithm. When searching for element x, we can compare the x and the root node:

1. If x equals the root node, then find x, stop the search (termination condition)

2. If x is a small root node, then search Zuozi

3. If x is greater than the root node, then search the right subtree

The binary search tree requires the most number of operations to be equal to the depth of the tree. The depth of the two-fork search tree for n nodes is at most n, with a minimum of log (n).

The following is a Java implementation of the two-fork search tree, and there are search, insert, delete, to find the largest point of the operation of the bar.

Deleting a node is relatively complex. After deleting a node, it is sometimes necessary to make some adjustments to restore the nature of the binary search tree (each node is no smaller than any element of its left subtree, and is no larger than any of its right subtrees).

    • Leaf nodes can be deleted directly.
    • When you delete a non-leaf node, such as Node 8 in, we can delete the largest element in the left subtree (or the largest element in the right tree) and use the deleted node to supplement the vacancy created by element 8. But the element may not be a leaf node, so the vacancy it generates requires additional elements ... Until you finally delete a leaf node. The above procedure can be implemented recursively.

Delete a node

Two-fork search tree after deleting a node

Import Java.util.arraylist;import Java.util.list;public class Binarysearchtree {//Tree root node private TreeNode root = null;//times Calendar Node List private list<treenode> nodelist = new arraylist<treenode> ();p Rivate class TreeNode {private int key; Private TreeNode leftchild;private TreeNode rightchild;private TreeNode parent;public TreeNode (int key, 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 ("The Tree is empty!");}} /** * Search: Query a given keyword in a binary lookup tree * * @param key * given keyword * @return match tree node of a given keyword */public TreeNode search (int key) {T  Reenode Pnode = Root;while (Pnode! = NULL && Pnode.key! = key) {if (Key < Pnode.key) {pnode = Pnode.leftchild;} else {pnode = Pnode.rightchild;}} return pnode;} /** * Minelemnode: Get the smallest keyword node in the binary lookup tree * * @return The minimum key node of the binary find tree * @throws Exception * If the tree is empty, throws an exception */public TreeN Ode Minelemnode (TreeNode 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 find tree * @throws Exception * If the tree is empty, throws an exception */public TreeN Ode Maxelemnode (TreeNode 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 under the sequence traversal orderPoint * * @param node * node in the given tree * @return If the node has a successor node in the sequence traversal order, it returns its successor node; otherwise null * @throws Exception */public TreeN Ode 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 * node in the given tree * @return If the node has a forward node in the sequence traversal order, the forward node is returned; otherwise null * @throws Exception */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 = P Arentnode;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 nothing is returned directly;}} if (Key < Parentnode.key) {parentnode.leftchild = Newnode;newnode.parent = parentnode;} else {parentnode.rightchild = n Ewnode;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 {Tr Eenode Pnode = Search (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 * node to delete * pre-condition: a given node already exists in the binary lookup tree * @throws Exception */private void Delete (Tree Node Pnode) throws ExceptIon {if (Pnode = = null) {return;} if (Pnode.leftchild = = NULL && Pnode.rightchild = = null) {//The node has no left child node or right child node treenode ParentNode = Pnode.parent. 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.parent 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.parent if (Pnode = = parentnode.leftchild) {parentnode.leftchild = Pnode.leftchild;pnode.rightchild.parent = ParentNode;} else {parentnode.rightchild = Pnode.leftchild;pnode.rightchild.parent = parentnode;} return;} If the node of the knot is not empty, the successor node of the node is deleted, and the node is replaced by the successor node TreeNode Successornode = successor.(Pnode);d elete (successornode);p node.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 * root node of a given binary lookup tree */private void Inordertraverse (TreeNode ro OT) {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 () {Stringbuild Er sbbuilder = new StringBuilder ("["); for (TreeNode p:inordertraverselist ()) {sbbuilder.append (p.key); Sbbuilder.appen D ("");} 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:inor Dertraverselist ()) {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[] {6, 3, 7, 2, 9};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 keywords:" + 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 ("******************************"); Testtraverse (BST);}   catch (Exception e) {System.out.println (E.getmessage ()); E.printstacktrace ();}}}

  

Java implementation two Tree search tree

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.