Advertisement
LoganBlackisle

BST_insertion

Jun 16th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. package prep_33_binarysearchtrees;
  2.  
  3. //Java program to demonstrate insert operation in binary search tree
  4. public class BST_insertion {
  5. /* Class containing left and right child of current node and key value */
  6. public class Node {
  7. int key;
  8. Node left, right;
  9.  
  10. public Node(int item) {
  11. key = item;
  12. left = right = null;
  13. }
  14. }
  15.  
  16. // Root of BST
  17. Node root;
  18.  
  19. // Constructor
  20. public BST_insertion() {
  21. root = null;
  22. }
  23.  
  24. // This method mainly calls insertRec()
  25. public void insert(int key) {
  26. root = insertRec(root, key);
  27. }
  28.  
  29. /* A recursive function to insert a new key in BST */
  30. public Node insertRec(Node root, int key) {
  31. if (root == null) { // If the tree is empty, return a new node
  32. root = new Node(key);
  33. return root;
  34. }
  35. if (key < root.key) // Otherwise, recur down the tree
  36. root.left = insertRec(root.left, key);
  37. else if (key > root.key)
  38. root.right = insertRec(root.right, key);
  39. return root; // return the (unchanged) node pointer
  40. }
  41.  
  42. // This method mainly calls InorderRec()
  43. public void inorder() {
  44. inorderRec(root);
  45. }
  46.  
  47. // A utility function to do inorder traversal of BST
  48. public void inorderRec(Node root) {
  49. if (root != null) {
  50. inorderRec(root.left);
  51. System.out.println(root.key);
  52. inorderRec(root.right);
  53. }
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement