Implement binary tree search tree in java and java Binary Tree

Source: Internet
Author: User

Implement binary tree search tree in java and java Binary Tree

 

Binary is a special tree. Each node of a binary tree can have a maximum of two subnodes:

Binary Tree

Because the number of subnodes of a binary tree is determined, it can be implemented directly in the memory. Each node has a left child node and a right child node ). The left subnode is the root node of the Left subtree, And the right subnode is the root node of the right subtree.

 

If we add an additional condition to the binary tree, we can get a special binary tree called binary search tree. Binary Search Tree requirements: each node is no smaller than any element in its left subtree and no larger than any element in its right subtree.

(If we assume that there are no repeated elements in the tree, the preceding 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, pay attention to the size of elements in the tree

The binary search tree can easily implement search algorithms. When searching for element x, we can compare x with the root node:

1. If x is equal to the root node, locate x and stop the search (termination condition)

2. If x is smaller than the root node, search for the left subtree.

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

The number of operations required by the binary search tree is equal to the depth of the tree. The depth of the Binary Search Tree of n nodes is n at most, and the minimum is log (n ).

 

The following is a binary search tree implemented in java with search, insert, and delete operations to find the maximum and minimum nodes.

Deleting a node is relatively complicated. After a node is deleted, some adjustments are required to restore the nature of the Binary Search Tree (each node is no smaller than any element in the left subtree, it is no larger than any element in its right subtree ).

  • Leaf nodes can be deleted directly.
  • When deleting a non-leaf node, such as node 8, we can delete the largest element (or the largest element in the right tree) in the left subtree ), use the deleted node to fill in the vacancies generated by element 8. However, this element may not be a leaf node, so the vacancy generated by it needs to be supplemented by other elements ...... Until the last leaf node is deleted. The above process can be implemented recursively.

Delete a node

Binary Search Tree After deleting a node

 

Import java. util. arrayList; import java. util. list; public class BinarySearchTree {// root node of the tree private TreeNode root = null; // traverse the node List private List <TreeNode> nodelist = new ArrayList <TreeNode> (); private 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 = ke Y; 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 whether the binary search tree is null. If it is null, true is returned. Otherwise, false is returned. **/public boolean isEmpty () {if (root = null) {return true;} else {return false ;}}/*** TreeEmpty: for some Binary Search Tree operations (such as deleting keywords), if the tree is empty, an exception is thrown. */Public void TreeEmpty () throws Exception {if (isEmpty () {throw new Exception ("the tree is empty! ") ;}}/*** Search: query the given keyword ** @ param key * for the given keyword * @ return for the given keyword in the binary search tree */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: obtain the minimum keyword node in the binary search tree ** @ return the minimum keyword node of the binary search tree * @ throws Exception * If the tree is empty, throw an Exception */public TreeNode 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: obtain the maximum keyword node in the binary search tree ** @ return the maximum keyword node of the binary search tree * @ throws Exception * If the tree is empty, throw an Exception */public TreeNode 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: obtain the successor node of a given node in the central order traversal order ** @ param node * node in the given tree * @ return if the node has a successor node in the central order traversal order, otherwise, return null * @ throws Exception */public TreeNode successor (TreeNode node) throws Exception {if (node = null) {return null ;} // if the right subtree of the node is not empty, its successor node is the smallest keyword node if (node. rightChild! = Null) {return minElemNode (node. rightChild) ;}// if the right subtree of the node is empty, TreeNode parentNode = node. parent; while (parentNode! = Null & node = parentNode. rightChild) {node = parentNode; parentNode = parentNode. parent;} return parentNode;}/*** precessor: obtain the frontend node of a given node in the central order traversal order ** @ param node * node in the given tree * @ return if the node exists in the central order traversal order, otherwise, return 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, the frontend node is the largest keyword node if (node. leftChild! = Null) {return maxElemNode (node. leftChild) ;}// if the left subtree of the node is empty, TreeNode parentNode = node. parent; while (parentNode! = Null & node = parentNode. leftChild) {node = parentNode; parentNode = parentNode. parent;} return parentNode;}/*** insert: insert the given keyword into the Binary Search Tree ** @ param key * given keyword */public void insert (int key) {TreeNode parentNode = null; TreeNode newNode = new TreeNode (key, 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;} if the else {// tree already contains a node that matches the given keyword, return is not returned directly;} if (key <parentNode. key) {parentNode. leftChild = newNode; newNode. parent = parentNode;} else {parentNode. rightChild = newNode; newNode. parent = parentNode;}/*** insert: Delete the tree node matching the given keyword from the Binary Search Tree ** @ param key * given keyword */public vo Id delete (int key) throws Exception {TreeNode pNode = search (key); if (pNode = null) {throw new Exception ("The key To be deleted does not exist in the tree! ");} Delete (pNode);}/*** delete: delete a given node from the binary search tree. ** @ param pNode * node to be deleted ** preconditions: The given node already exists * @ throws Exception */private void delete (TreeNode pNode) in the binary search tree) throws Exception {if (pNode = null) {return;} if (pNode. leftChild = null & pNode. rightChild = null) {// No left child node or right child node TreeNode parentNode = pNode. parent; if (pNode = parentNode. leftChild) {parentNode. leftChild = null;} else {parentNod E. rightChild = null;} return;} if (pNode. leftChild = null & pNode. rightChild! = Null) {// The left child node of the node is empty, and the right child node is not 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 left child node of the node is not empty, and the 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 left and right child nodes of the node are not empty, the child nodes of the node are deleted, replace this node with the successor node TreeNode successorNode = successor (pNode); delete (successorNod E); pNode. key = successorNode. key;}/*** inOrderTraverseList: obtains the List of vertices in the central order of the Binary Search Tree. ** @ return the node List in the central order of the binary search tree */public List <TreeNode> inOrderTraverseList () {if (nodelist! = Null) {nodelist. clear ();} inOrderTraverse (root); return nodelist;}/*** inOrderTraverse: traverse the given binary search tree in a central order ** @ param root * root node of the given binary search tree */private void inOrderTraverse (TreeNode root) {if (root! = Null) {inOrderTraverse (root. leftChild); nodelist. add (root); inOrderTraverse (root. rightChild) ;}}/*** toStringOfOrderList: Get the ordered list of keywords in the binary search tree ** @ return the ordered list of keywords in the binary search tree */public String toStringOfOrderList () {StringBuilder sbBuilder = new StringBuilder ("["); for (TreeNode p: inOrderTraverseList () {sbBuilder. append (p. key); sbBuilder. append ("");} sbBuilder. append ("]"); return sbBuilder. toString ();}/*** Obtain the String representation of the binary search 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 ("local node:" + pNode); System. out. Println ("frontend 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 ("Convert binary search tree to ordered list:" + bst. toStringOfOrderList ();} public static void main (String [] args) {try {BinarySearchTree bst = new BinarySearchTree (); System. out. println ("is the search 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 search 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 ("Maximum 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 ();}}}

  

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.