Java Implementation of Binary Search Tree

Source: Internet
Author: User

Java Implementation of Binary Search Tree
To gain a better understanding of the Binary Search Tree, the blogger wrote a binary search tree in Java. If you are interested, you can discuss it together. First, what is the binary search tree? What is its use? The binary search tree, also known as the binary sorting tree, has a data structure of one parent node pointer, one left child pointer, and one child pointer, there is also our own data, because only two children are left and right, so it is called a binary tree. On this basis, the binary tree meets another condition: the left child of each node is not greater than this node & the right child of each node is greater than this node. In this way, we can traverse the tree in the middle order to sort the keys from small to large ...... So the question is, I have a linear table with a linked list. What should I do? Two words! Efficiency! Compared to a linear table, if you want to search for a key, you need to execute a linear time. The algorithm complexity is O (n). In the Binary Search Tree, the algorithm efficiency is O (lgn )! This is an attractive number. I will use Java to implement the following binary search tree. You will naturally understand why the algorithm complexity is O (lgn. Secondly, to write a data structure, you must add, delete, query, and modify the data structure. The following is my idea: Create a tree: I create a binary search tree by inserting a node. Search node: Start from the root node and compare the key. When it is small, it will go to the left. When it is big, it will go to the right. When it is reached, it will not be available at the leaf node, the tree does not have any node to be searched. Modify node: the modification is actually a query. After the query, the data part of the node is changed. I will not implement it again here. Delete a node: this should be the most difficult one, so I need to explain it in detail. (sorry, I am too lazy to use the software to draw a picture. I will just talk about it.): When we want to delete a node, the node is a leaf node, which is the simplest. Just release the node. (Delete 9) This node only has the left child. This is also simple. simply replace the left subtree. (Delete 3) this node only has the right child, same as above. (Delete 8) This node has left and right children. When this happens (delete 7), we need to find the successor node of this node (because the right subtree must exist, so find it in the right subtree), and then replace this successor node with the node to be deleted, then, execute the delete operation on the next node (recursive delete operation is enough ). Found? Now, my solution is to analyze the problem from top to bottom ...... From top to bottom, refinement is a great idea! Now the question is coming! How to find the successor node? Let's analyze the following two cases: when a node has a right child, the next node is in the right subtree, it is the minimum node of the right subtree. When the node does not have the right child, the subsequent node meets this condition: this successor node is the ancestor of this node & this node is located in the left subtree of this node (the successor node of 9 in the middle is 12) alas! The problem is coming again! What about the minimum node! Very easy! When you find the shortest point of a tree, you must start from the root node of the tree and continue to the left subtree to find its minimum node! Now the problem is solved gradually! The Node Deletion function is complete! Finally, there is no code to say a hammer. Let's get the code! First, write a test class: View Code. Then, the binary search tree: 1 public class BinTree {2 Node root = null; 3 private class Node {4 Node parent = null; 5 Node leftChild = null; 6 Node rightChild = null; 7 int key; 8 public Node (int data) {9 this. key = data; 10} 11} 12 public BinTree (int [] datas) {13 buildTree (datas); 14} 15 private void buildTree (int [] datas) {16 for (int I = 0; I <datas. length; I ++) {17 Node node = new Node (datas [I] ); 18 insertNode (node); 19} 20} 21 private void insertNode (Node node) {// insert Node 22 node next = this. root; 23 Node cur = null; // used to save the current Node 24 while (next! = Null) {// when the leaf knot is reached, confirm the location! 25 cur = next; 26 if (node. key> = cur. key) {27 next = next. rightChild; 28} else {29 next = next. leftChild; 30} 31} 32 node. parent = cur; // insert this node! 33 if (cur = null) {34 this. root = node; // This tree is an empty tree, so this is the root node 35} else if (node. key> = cur. key) {36 cur. rightChild = node; 37} else {38 cur. leftChild = node; 39} 40} 41/* 42 * insert a number 43 */44 public void insert (int data) {45 Node node = new Node (data ); 46 System. out. println ("insert node:" + data); 47 insertNode (node); 48 this. midOrderTraverse (); 49} 50 51/* 52 * traverse 53 */54 public void preOrderTraverse () {55 System. o Ut. println ("sequential traversal:"); 56 preOrderTraverse (root); 57 System. out. println (); 58} 59 private void preOrderTraverse (Node node) {// traverse 60 if (node! = Null) {61 System. out. print ("-" + node. key + "-"); 62 preOrderTraverse (node. leftChild); 63 preOrderTraverse (node. rightChild); 64} 65} 66/* 67 * traverse 68 */69 public void midOrderTraverse () {70 System. out. println ("sequential traversal:"); 71 midOrderTraverse (root); 72 System. out. println (); 73} 74 private void midOrderTraverse (Node node) {// traverse 75 if (node! = Null) {76 midOrderTraverse (node. leftChild); 77 System. out. print ("-" + node. key + "-"); 78 midOrderTraverse (node. rightChild); 79} 80 81} 82 83/* 84 * traverse 85 */86 public void postOrderTraverse () {87 System. out. println ("post-order traversal:"); 88 postOrderTraverse (root); 89 System. out. println (); 90} 91 private void postOrderTraverse (Node node) {// traverse 92 if (node! = Null) {93 System. out. print ("-" + node. key + "-"); 94 postOrderTraverse (node. leftChild); 95 postOrderTraverse (node. rightChild); 96} 97} 98 99/* 100 * search node 101 */102 public void search (int data) {103 System. out. println ("you are looking for:" + data); 104 Node node; 105 if (node = searchNode (new Node (data) = null) {106 System. out. println ("this node is not in the tree! "); 107} else {108 System. out. println (" Search "+ node. key +" successful! "); 109} 110} 111 112 private Node searchNode (Node node) {// private for internal call, search Node 113 if (Node = null) {114 System. out. println ("the input is null. An error occurred while searching! "); 115} else {116 if (root = null) {117 System. out. println (" this tree is an empty tree! "); 118} else {// start searching 119 boolean isFound = false; 120 Node x = root; 121 Node y = null; 122 while (! IsFound & x! = Null) {// It ends when the leaf node is found or not found! 123 y = x, 124 if (node. key = x. key) {125 isFound = true; 126} else {// search for the 127 if (node. key> x. key) {128 x = x. rightChild; 129} else {130 x = x. leftChild; 131} 132} 133} 134 if (isFound) {// if not found, return null135 return y; 136} 137} 138 return null at the end; 140} 141 142/* 143 * get the maximum value 144 */145 public void getMax () {146 Node node; 147 if (node = getMaxNode (root) = null) {148 System. out. println ("this tree is empty! "); 149} else {150 System. out. println ("the largest node is:" + node. key); 151} 152 153} 154 155 private Node getMaxNode (Node node) {// obtain the maximum value of 156 if (node! = Null) {157 Node x = node; 158 Node y = null; 159 while (x! = Null) {// Traverse right until the bottom is the maximum value! 160 y = x; 161 x = x. rightChild; 162} 163 return y; 164} 165 return null; 166} 167 168/* 169 * get minimum value 170 */171 public void getMin () {172 Node node; 173 if (node = getMinNode (root) = null) {174 System. out. println ("this tree is empty! "); 175} else {176 System. out. println ("the smallest node is:" + node. key); 177} 178} 179 private Node getMinNode (Node node) {// get the minimum value of 180 if (node! = Null) {181 Node x = node; 182 Node y = null; 183 while (x! = Null) {// always traverse to the left until the bottom is the minimum value! 184 y = x; 185 x = x. leftChild; 186} 187 return y; 188} 189 return null; 190} 191 192/* 193 * Get the precursor node 194 */195 public void getPre (int data) {196 Node node = null; 197 System. out. println (data + "precursor node:"); 198 if (Node = getPreNode (searchNode (new node (data) = null) {199 System. out. println ("this node does not exist or there is no precursor node! "); 200} else {201 System. out. the frontend node of println (data + "is:" + node. key); 202} 203} 204 205 private Node getPreNode (Node node) {// obtain the frontend node 206 if (Node = null) {207 return null; 208} 209 if (node. leftChild! = Null) {// when there is a left child, the precursor node is the maximum value of the Left subtree 210 return getMaxNode (node. leftChild); 211} else {// when there is no left child, the precursor node is its ancestor, and it is in the right subtree of this ancestor. In this sentence, you can understand 212 Node x = node; 213 Node y = node. parent; 214 while (y! = Null & x = y. leftChild) {215 x = y; 216 y = y. parent; 217} 218 return y; 219} 220 221/* 222 * Get the successor Node 223 */224 public void getPost (int data) {225 node Node = null; 227 System. out. println (data + "successor node:"); 228 if (Node = getPostNode (searchNode (new node (data) = null) {229 System. out. println ("this node does not exist or there is no successor node! "); 230} else {231 System. out. the successor node of println (data + "is:" + node. key); 232} 233} 234 235 private Node getPostNode (Node node) {// obtain the successor node 236 if (Node = null) {237 return null; 238} 239 if (node. rightChild! = Null) {// when there is a right child, the precursor node is the minimum value of 240 return getMinNode (node. rightChild); 241} else {// when there is no right child, the successor node is its ancestor, and it is in the left subtree of this ancestor. In this sentence, you can understand 242 Node x = node; 243 Node y = node. parent; 244 while (y! = Null & x = y. rightChild) {245 x = y; 246 y = y. parent; 247} 248 return y; 249} 250 251 252/* 253 * delete Node 254 */255 public void delete (int data) {256 node; 258 if (node = searchNode (new Node (data) = null) {// note! It cannot be a new node! You must find this node from the tree! New indicates that the 259 System. out. println ("this node does not exist in the binary tree! "); 260 return; 261} 262 deleteNode (node); 263 System. out. println ("delete node" + data + ":"); 264 this. midOrderTraverse (); 265} 266 267 268 private void deleteNode (Node node) {269 if (node = null) {270 System. out. println ("delete node cannot be blank! "); 271 return; 272} 273 replacedNode (node); 274} 275 276 private void replacedNode (Node node) {// replace node 277 if (node. leftChild! = Null278 & node. rightChild! = Null) {// when there are left and right children, replace 279 replacedNodeOfPost (node) with the successor node; 280} 281 else282 {283 if (node. leftChild! = Null) {// if there is only a left child, replace 284 node = node. leftChild; 285} else if (node. rightChild! = Null) {// if there is only a right child, replace 286 node = node with a subtree. rightChild; 287} else {// when there are no children left or right, the node 288 freeNode (node) is directly released ); 289} 290} 291} 292 293 294 private void freeNode (Node node) {// release the node and disconnect its link to the parent node 295 if (Node = node. parent. leftChild) {296 node. parent. leftChild = null; 297} else {298 node. parent. rightChild = null; 299} 300} 301 private void replacedNodeOfPost (Node node Node) {302 Node y = this. getPostNode (node); // find the successor node 304 nod E. key = y. key; 305 replacedNode (y); // after the key is replaced, the current node is replaced again recursively! 306} 307 308} finally the test result: -------------------- split line ------------------------- first sequential traversal:-Skip-middle sequential traversal:-Skip-back sequential traversal:-ignore-insert node: 15 middle order traversal: -2--3--4--4--5--6--7--8--9--12--15-if you want to search for "7", the search is successful! You need to find that the node does not exist in the 100 tree! The largest node is: 15 the smallest node is: 27 the precursor node: 7 the precursor node is: 62 the precursor node: this node does not exist or there is no precursor node! 7 successor node: 7 successor node: 815 successor node: this node does not exist or there is no successor node! After node 5 is deleted, the node does not exist in the middle-order traversal:-2--3--4--4--6--7--8--9--12--15-binary 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.