Guest User

Untitled

a guest
Jan 23rd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. //params: key of node to be inserted, parent node
  2. public void insert(int newKey, TreeNode parent){
  3.  
  4. //if the root of the tree is empty, insert at root
  5. if(this.getRoot() == null){
  6. this.root = new TreeNode(newKey, null, null);
  7. }
  8.  
  9. //if the node is null, insert at this node
  10. else if(parent == null)
  11. parent = new TreeNode(newKey, null, null);
  12.  
  13.  
  14. else{
  15. //if the value is less than the value of the current node, call insert on the node's left child
  16. if(newKey < parent.getKey()) {
  17. insert(newKey, parent.getLeft());
  18. }
  19. //greater than value of current node, call insert on node's right child
  20. else if(newKey > parent.getKey()){
  21. insert(newKey, parent.getRight());
  22. }
  23. //same as value of current node, increment iteration field by one
  24. else if(newKey == parent.getKey())
  25. parent.incrementIterations();
  26. }
  27.  
  28. }
  29.  
  30. public Node insertNode(Node head, int data) {
  31.  
  32. if(head == null){
  33. head = new Node();
  34. head.data = data;
  35. return head;
  36. }
  37. if(head.data < data) {
  38. head.right = insertNode(head.right,data);
  39. } else {
  40. head.left = insertNode(head.left, data);
  41. }
  42. return head;
  43. }
Add Comment
Please, Sign In to add comment