Binary search tree (Java implementation)

Source: Internet
Author: User
Tags delete key

Two fork search tree basic Operations
The number of nodes in the tree to determine whether the node is inserted into the empty tree to insert a new node in the Key-value tree if a key in the key return tree exists in the value value values in the first order traversal sequence traversal sequential traversal sequence traversal in order to find the key to the smallest node in the tree key in the largest node delete the key node in the tree Delete a node in the
Code:
/** * @param <Key> Key generics * @param <Value> value Generic */public class Binarysearchtree<key extends Comparable<? Super Key>, value> {private class Node {private key key;//key, equivalent to the word in the dictionary private value value;//value , equivalent to the explanation in the dictionary private Node left; Left child node private node right;//right child node//node constructor public node (key key, value value) {this.ke            y = key;            This.value = value;            This.left = null;        This.right = null;        }//getters and Setters public Key GetKey () {return key;        } public void Setkey (key key) {This.key = key;        } public Value GetValue () {return value;        } public void SetValue (value value) {this.value = value;        } public Node GetLeft () {return to left;        public void Setleft (Node-left) {this.left = left; } public Node GetRight () {           return right;        public void Setright (Node right) {this.right = right;                    } @Override Public String toString () {return "node{" + "key=" + key +        ", value=" + Value + '} '; }} private Node root; Binary search tree root node private int size;        Number of nodes in binary search tree//Tree constructor public Binarysearchtree () {this.root = null;    this.size = 0;    }//To find the number of nodes in the tree public int size () {return this.size;    }//Determine if the node is empty public boolean isEmpty () {return this.size = = 0;            }//Insert Key-value private node Insert (node node, key key, value value) in the tree with node node root (subtree) {if (node = = null) {            size++;        return new Node (key, value);        } else if (Node.key.compareTo (key) > 0) {node.setleft (insert (Node.getleft (), key, value)); } else if (Node.key.compareTo (key) < 0) {node.setright (insert (node.getRight (), key, value));        } else {//equal when node.value = value;    } return node;    }//Insert new node into the tree key-value public void Insert (key key, value value) {root = insert (root, Key, value); }//Node node is the root of the tree (subtree) If there is a Key private Boolean contain (node node, key key) {if (node = = null) {Retu        RN false;        } else if (Node.key.compareTo (key) = = 0) {return true;        } else if (Node.key.compareTo (key) > 0) {return contain (Node.getleft (), key);        } else {return contain (Node.getright (), key);    }}//Tree exists Key public boolean contain (key key) {return contain (root, key); }//Returns the value of Key in the tree (subtree) where node node is rooted, private value search (node node, key key) {if (node = = null) {R        Eturn null;        } else if (Node.getkey (). CompareTo (key) = = 0) {return node.getvalue (); } else if (Node.getkey (). CompareTo (key) > 0) {return SEArch (Node.getleft (), key);        } else {return search (Node.getright (), key);    }}//Returns the value of key in the tree to public value search (key key) {return search (root, key);        }//Sequence traversal private void preorder (node node) {if (node = = null) return;        System.out.println (Node.key);        Preorder (Node.getleft ());    Preorder (Node.getright ());    }//ordinal traverse public void preorder () {preorder (root);        }//middle order traverse private void Inorder (node node) {if (node = = null) return;        Inorder (Node.getleft ());        System.out.println (Node.getkey ());    Inorder (Node.getright ());    }//middle order traverse public void Inorder () {inorder (root);        }//Subsequent traversal of private void Postorder (node node) {if (node = = null) return;        Postorder (Node.getleft ());        Postorder (Node.getright ());    System.out.println (Node.getkey ());    }//Subsequent traversal of public void Postorder () {postorder (root); }//Sequence traversal public voiD Levelorder () {if (root = null) return;        java.util.linkedlist<node> queue = new java.util.linkedlist<> ();        Queue.add (root);            while (!queue.isempty ()) {node node = Queue.pop ();            SYSTEM.OUT.PRINTLN (node);            if (node.getleft () = null) {Queue.add (Node.getleft ());            } if (node.getright () = null) {Queue.add (Node.getright ()); }}}//In a tree with node root, key minimum node private node Minnode (node node) {if (node.getleft () = = null) return No        De    Return Minnode (Node.getleft ());    }//Tree key Min node public node Minnode () {return minnode (root);        }//node is the root of the tree, key the largest node private node Maxnode (node node) {if (node.getright () = = null) return Node;    Return Maxnode (Node.getright ());    }//Tree key node public node Maxnode () {return maxnode (root); }//Delete node-rooted tree (subtree) with key minimum node private node removemin (node node) {if (node = = NULL) return null;            if (node.getleft () = = null) {node Rightnode = Node.getright ();            Node.setright (NULL);            size--;        return rightnode;        } node.setleft (Removemin (Node.getleft ()));    return node;    }//Delete key of the smallest node in the tree public void Removemin () {root = Removemin (root);        }//Delete node root tree (subtree) key largest node private node Removemax (node node) {if (node = = NULL) return null;            if (node.getright () = = null) {node Leftnode = Node.getleft ();            Node.setleft (NULL);            size--;        return leftnode;        } node.setright (Removemax (Node.getright ()));    return node;    }//Delete key in tree the largest node public void Removemax () {root = Removemax (root);        }//delete a node private node remove (node node, key key) {if (node = = NULL) return null; if (Key.compareto (Node.key) < 0) {//if smaller than the root, remove the left subtree and return to the root node.setleft (remove (node.geTLeft (), key));        return node;            } else if (Key.compareto (Node.key) > 0) {//If larger than root, go to right subtree Delete, then return root node.setright (remove (Node.getright (), key));        return node; } else {//key = = Node.key//If the root key of the subtree is equal if (node.getleft () = = null) {//Determine if the root of the current subtree has left dial hand tree node                Rightnode = Node.getright ();                Node.setright (NULL);                size--;            return rightnode;                } else if (node.getright () = = null) {//Determines whether the root of the current subtree has a right subtree node Leftnode = Node.getleft ();                Node.setleft (NULL);                size--;            return leftnode;                } else {//If the current subtree has both a left dial hand tree and a right subtree Node successor = Minnode (Node.getright ());//Search for successor nodes, that is, the smallest node in the right sub-tree                Successor = new node (Successor.getkey (), Successor.getvalue ());//Create a new one that is exactly the same as the successor, in order to replace the size++;//it is equivalent to adding a node. Successor.setright (Removemin (Node.getright ()));//delete subsequent nodes and connect to the original right succesSor.setleft (Node.getleft ());//connected to the original left node.left = Node.right = null;//The original node has been replaced, can not. size--;//is equivalent to deleting a node return successor;//the current new subtree is successor}}} public void Remove (K    EY key) {root = remove (root, key); } public static void Main (string[] args) {//Build a binary search tree binarysearchtree<string, string> BST = new B        Inarysearchtree<> ();        Insert Data Bst.insert ("Dog", "dogs, an Animal");        Bst.insert ("Password", "password");        Bst.insert ("Cat", "cat, an Animal");        Bst.insert ("Cup", "mug");        Bst.insert ("Tom", "Tom", "Cat and Mouse");        Bst.insert ("Jerry", "Jerry, mouse in Cat and mouse");        Bst.insert ("A", "the first of the 26 English letters");         Search () System.out.println (Bst.search ("a"));//26 the first System.out.println (Bst.search ("dog") in the English alphabet;//dog, an animal System.out.println (Bst.search ("ttttt"));//null//contain () System.out.println (Bst.contain ("Cup"));// True System.out.println (Bst.contain ("Tom"));//true System.out.println (Bst.contain ("tttttt"));//false//maxnode () system.out.p Rintln (Bst.maxnode ());//node{key=tom, value= Tom, cat and Mouse Cats}//minnode () System.out.println (Bst.minnode ())//no        De{key=a, value=26 the first of the English letters}//removemax () Bst.removemax ();        System.out.println (Bst.maxnode ());//node{key=password, value= password}//removemin () Bst.removemin ();        System.out.println (Bst.minnode ());//node{key=cat, value= Cat, an Animal}//size () System.out.println (Bst.size ());//5        Levelorder () Bst.levelorder ();        Remove ();        System.out.println ("--------------");        Bst.remove ("password");    Bst.preorder (); }}

  

Binary search tree (Java implementation)

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.