2016-06-28

Binary search tree implementation using java




Definition: A binary search tree (BST) is a binary tree where each node has a Comparable key (and an associated value) and satisfies the restriction that the key in any node is larger than the keys in all nodes in that node’s left subtree and smaller than the keys in all nodes in that node’s right subtree.

(Binary search trees main operations - Searching, Insertion, Deletion, Traversaland  Verification)


  1. public class BST<Key extends Comparable<Key>, Value>
  2. {
  3. private class Node
  4. {
  5. private Key key; // key
  6. private Value val; // associated value
  7. private Node left, right; // links to subtrees
  8. private int N; // nodes in subtree
  9. public Node(Key key, Value val, int N)
  10. { this.key = key;
  11.  this.val = val; 
  12.  this.N = N;
  13.  }
  14. }
  15. private Node root; // root of node of BST

  16. public int size() //return size of BST
  17. { return size(root); 
  18. }
  19. private int size(Node x)
  20. {
  21. if (x == null) return 0;
  22. else return x.N;
  23. }
  24. public Value get(Key key)
  25. { return get(root, key); }
  26. private Value get(Node x, Key key)
  27. { // Return value associated with key in the subtree rooted at x;
  28. // return null if key not present in subtree rooted at x.
  29. if (x == null) return null;
  30. int cmp = key.compareTo(x.key);
  31. if (cmp < 0) return get(x.left, key);
  32. else if (cmp > 0) return get(x.right, key);
  33. else return x.val;
  34. }
  35. public void insert(Key key, Value val)
  36. { // Search for key. Update value if found; grow table if new.
  37. root = insert(root, key, val);
  38. }
  39. private Node insert(Node x, Key key, Value val)
  40. {
  41. // Change key’s value to val if key in subtree rooted at x.
  42. // Otherwise, add new node to subtree associating key with val.
  43. if (x == null) return new Node(key, val, 1);
  44. int cmp = key.compareTo(x.key);
  45. if (cmp < 0) x.left = insert(x.left, key, val);
  46. else if (cmp > 0) x.right = insert(x.right, key, val);
  47. else x.val = val;
  48. x.N = size(x.left) + size(x.right) + 1;
  49. return x;
  50. }
  51. //chacking if a tree is binary search tree or not
  52. bool isBST(Node node, int minKey, int maxKey) {
  53.     if(node == NULL) return true;
  54.     if(node.key < minKey || node.key > maxKey) return false;
  55.     
  56.     return isBST(node.left, minKey, node.key) && isBST(node.right, node.key, maxKey);
  57. }
  58. }
Example  :

      Node child1 = new Node(1, 1, 0);
   insert(child1, 1, 1);


No comments:

Post a Comment