Advertisement
TonyT8

Untitled

Dec 7th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. private void someMethod(T newEntry) {
  2. /*
  3. * Setting up the necessary variables
  4. */
  5. BinaryNode<T> currentNode = getRootNode();
  6. BinaryNode<T> previousNode = getRootNode();
  7. BinaryNode<T> newNode = new BinaryNode<T>(newEntry);
  8.  
  9. /*
  10. * Searching for the end of the binary search tree.
  11. *
  12. * Current will first be tested to see if it's null. Then previousNode is going to keep track of currentNode's position.
  13. * Next step was to see where the currentNode will head next left or right using the compareTo method from Comparable.
  14. * If the currentNode.data is greater than or equal to the incoming newEntry (some positive Integer or zero respectively),
  15. * then the currentNode should look at the left child and right child otherwise (some negative Integer).
  16. *
  17. * The while loop exits after currentNode is set to NULL. After this the currentNode is set back to the previousNode.
  18. *
  19. * Finally it's the matter of comparing the currentData and the newEntry to see whether to add to the left or right.
  20. *
  21. * Side note: reversing the compareTo variables might have been easier to understand in hindsight.
  22. */
  23.  
  24. while (currentNode != null) {
  25.  
  26. previousNode = currentNode;
  27.  
  28. if (currentNode.getData().compareTo(newEntry) >= 0) {
  29.  
  30. currentNode = currentNode.getLeftChild();
  31.  
  32. } else {
  33.  
  34. currentNode = currentNode.getRightChild();
  35. }
  36.  
  37. }
  38.  
  39. /*
  40. * The while loop exits after currentNode is set to NULL. After this the currentNode is set back to the previousNode.
  41. *
  42. * Finally it's the matter of comparing the currentData and the newEntry to see whether to add to the left or right.
  43. *
  44. * Side note: reversing the compareTo variables might have been easier to understand in hindsight.
  45. */
  46.  
  47. currentNode = previousNode;
  48.  
  49. if (currentNode.getData().compareTo(newEntry) >= 0) {
  50. currentNode.setLeftChild(newNode);
  51. } else {
  52. currentNode.setRightChild(newNode);
  53. }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement