Java Program to Implement ScapeGoat Tree

«
»
This is a Java Program to implement ScapeGoat Tree. A scapegoat tree is a self-balancing binary search tree which provides worst-case O(log n) lookup time, and O(log n) amortized insertion and deletion time.

Here is the source code of the Java program to implement ScapeGoat tree. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  * Java Program to Implement ScapeGoat Tree
  3.  */
  4.  
  5. import java.util.Scanner;    
  6.  
  7. /* Class SGTNode */
  8. class SGTNode    
  9. {
  10.     SGTNode right, left, parent;
  11.     int value;
  12.  
  13.     /* Constructor */
  14.     public SGTNode(int val)
  15.     {
  16.         value = val;
  17.     }
  18. }
  19.  
  20. /* Class ScapeGoatTree */
  21. class ScapeGoatTree
  22. {
  23.     private SGTNode root;
  24.     private int n, q;
  25.  
  26.     /* Constructor */    
  27.     public ScapeGoatTree()
  28.     {
  29.         root = null;
  30.         // size = 0
  31.         n = 0;        
  32.     }
  33.     /* Function to check if tree is empty */
  34.     public boolean isEmpty()
  35.     {
  36.         return root == null;
  37.     }
  38.     /* Function to clear  tree */
  39.     public void makeEmpty()
  40.     {
  41.         root = null;
  42.         n = 0;
  43.     }    
  44.     /* Function to count number of nodes recursively */
  45.     private int size(SGTNode r)
  46.     {
  47.         if (r == null)
  48.             return 0;
  49.         else
  50.         {
  51.             int l = 1;
  52.             l += size(r.left);
  53.             l += size(r.right);
  54.             return l;
  55.         }
  56.     }
  57.     /* Functions to search for an element */
  58.     public boolean search(int val)
  59.     {
  60.         return search(root, val);
  61.     }
  62.     /* Function to search for an element recursively */
  63.     private boolean search(SGTNode r, int val)
  64.     {
  65.         boolean found = false;
  66.         while ((r != null) && !found)
  67.         {
  68.             int rval = r.value;
  69.             if (val < rval)
  70.                 r = r.left;
  71.             else if (val > rval)
  72.                 r = r.right;
  73.             else
  74.             {
  75.                 found = true;
  76.                 break;
  77.             }
  78.             found = search(r, val);
  79.         }
  80.         return found;
  81.     }
  82.     /* Function to return current size of tree */   
  83.     public int size() 
  84.     {
  85.         return n;
  86.     }
  87.     /* Function for inorder traversal */
  88.     public void inorder()
  89.     {
  90.         inorder(root);
  91.     }
  92.     private void inorder(SGTNode r)
  93.     {
  94.         if (r != null)
  95.         {
  96.             inorder(r.left);
  97.             System.out.print(r.value +" ");
  98.             inorder(r.right);
  99.         }
  100.     }
  101.     /* Function for preorder traversal */
  102.     public void preorder()
  103.     {
  104.         preorder(root);
  105.     }
  106.     private void preorder(SGTNode r)
  107.     {
  108.         if (r != null)
  109.         {
  110.             System.out.print(r.value +" ");
  111.             preorder(r.left);             
  112.             preorder(r.right);
  113.         }
  114.     }
  115.     /* Function for postorder traversal */
  116.     public void postorder()
  117.     {
  118.         postorder(root);
  119.     }
  120.     private void postorder(SGTNode r)
  121.     {
  122.         if (r != null)
  123.         {
  124.             postorder(r.left);             
  125.             postorder(r.right);
  126.             System.out.print(r.value +" ");
  127.         }
  128.     }     
  129.     private static final int log32(int q) 
  130.     {
  131.         final double log23 = 2.4663034623764317;
  132.         return (int)Math.ceil(log23*Math.log(q));
  133.     }
  134.     /* Function to insert an element */
  135.     public boolean add(int x) 
  136.     {
  137.         /* first do basic insertion keeping track of depth */
  138.         SGTNode u = new SGTNode(x);
  139.         int d = addWithDepth(u);
  140.         if (d > log32(q)) {
  141.             /* depth exceeded, find scapegoat */
  142.             SGTNode w = u.parent;
  143.             while (3*size(w) <= 2*size(w.parent))
  144.                 w = w.parent;
  145.             rebuild(w.parent);
  146.         }
  147.         return d >= 0;
  148.     }
  149.     /* Function to rebuild tree from node u */
  150.     protected void rebuild(SGTNode u) 
  151.     {
  152.         int ns = size(u);
  153.         SGTNode p = u.parent;
  154.         SGTNode[] a = new SGTNode[ns];
  155.         packIntoArray(u, a, 0);
  156.         if (p == null) 
  157.         {
  158.             root = buildBalanced(a, 0, ns);
  159.             root.parent = null;
  160.         } 
  161.         else if (p.right == u) 
  162.         {
  163.             p.right = buildBalanced(a, 0, ns);
  164.             p.right.parent = p;
  165.         } 
  166.         else 
  167.         {
  168.             p.left = buildBalanced(a, 0, ns);
  169.             p.left.parent = p;
  170.         }
  171.     }
  172.     /* Function to packIntoArray */
  173.     protected int packIntoArray(SGTNode u, SGTNode[] a, int i) 
  174.     {
  175.         if (u == null) 
  176.         {
  177.             return i;
  178.         }
  179.         i = packIntoArray(u.left, a, i);
  180.         a[i++] = u;
  181.         return packIntoArray(u.right, a, i);
  182.     }
  183.     /* Function to build balanced nodes */
  184.     protected SGTNode buildBalanced(SGTNode[] a, int i, int ns) 
  185.     {
  186.         if (ns == 0)
  187.             return null;
  188.         int m = ns / 2;
  189.         a[i + m].left = buildBalanced(a, i, m);
  190.         if (a[i + m].left != null)
  191.             a[i + m].left.parent = a[i + m];
  192.         a[i + m].right = buildBalanced(a, i + m + 1, ns - m - 1);
  193.         if (a[i + m].right != null)
  194.             a[i + m].right.parent = a[i + m];
  195.         return a[i + m];
  196.     }
  197.     /* Function add with depth */
  198.     public int addWithDepth(SGTNode u) 
  199.     {
  200.         SGTNode w = root;
  201.         if (w == null) 
  202.         {
  203.             root = u;
  204.             n++; 
  205.             q++;
  206.             return 0;
  207.         }
  208.         boolean done = false;
  209.         int d = 0;
  210.         do {
  211.  
  212.             if (u.value < w.value) 
  213.             {
  214.                 if (w.left == null) 
  215.                 {
  216.                     w.left = u;
  217.                     u.parent = w;
  218.                     done = true;
  219.                 } 
  220.                 else 
  221.                 {
  222.                     w = w.left;
  223.                 }
  224.             } 
  225.             else if (u.value > w.value) 
  226.             {
  227.                 if (w.right == null) 
  228.                 {
  229.                     w.right = u;
  230.                     u.parent = w;
  231.                     done = true;
  232.                 }
  233.                 w = w.right;
  234.             } 
  235.             else 
  236.             {
  237.                 return -1;
  238.             }
  239.             d++;
  240.         } while (!done);
  241.         n++; 
  242.         q++;
  243.         return d;
  244.     }
  245. }
  246.  
  247. public class ScapeGoatTreeTest
  248. {
  249.     public static void main(String[] args)
  250.     {                 
  251.         Scanner scan = new Scanner(System.in);
  252.         /* Creating object of ScapeGoatTree */
  253.         ScapeGoatTree sgt = new ScapeGoatTree(); 
  254.         System.out.println("ScapeGoat Tree Test\n");          
  255.         char ch;
  256.         /*  Perform tree operations  */
  257.         do    
  258.         {
  259.             System.out.println("\nScapeGoat Tree Operations\n");
  260.             System.out.println("1. insert ");
  261.             System.out.println("2. count nodes");
  262.             System.out.println("3. search"); 
  263.             System.out.println("4. check empty");
  264.             System.out.println("5. make empty");
  265.  
  266.             int choice = scan.nextInt();            
  267.             switch (choice)
  268.             {
  269.             case 1 : 
  270.                 System.out.println("Enter integer element to insert");
  271.                 sgt.add( scan.nextInt() );                     
  272.                 break;                                                    
  273.             case 2 : 
  274.                 System.out.println("Nodes = "+ sgt.size());
  275.                 break; 
  276.             case 3 : 
  277.                 System.out.println("Enter integer element to search");
  278.                 System.out.println("Search result : "+ sgt.search( scan.nextInt() ));
  279.                 break;                           
  280.             case 4 :  
  281.                 System.out.println("Empty status = "+ sgt.isEmpty());
  282.                 break;
  283.             case 5 :  
  284.                 System.out.println("\nTree cleared\n");
  285.                 sgt.makeEmpty();
  286.                 break;             
  287.             default : 
  288.                 System.out.println("Wrong Entry \n ");
  289.                 break;           
  290.             }
  291.             /*  Display tree  */ 
  292.             System.out.print("\nPost order : ");
  293.             sgt.postorder();
  294.             System.out.print("\nPre order : ");
  295.             sgt.preorder();
  296.             System.out.print("\nIn order : ");
  297.             sgt.inorder();
  298.  
  299.             System.out.println("\nDo you want to continue (Type y or n) \n");
  300.             ch = scan.next().charAt(0);                        
  301.         } while (ch == 'Y'|| ch == 'y');               
  302.     }
  303. }

ScapeGoat Tree Test
 
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
34
 
Post order : 34
Pre order : 34
In order : 34
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
67
 
Post order : 67 34
Pre order : 34 67
In order : 34 67
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
11
 
Post order : 11 67 34
Pre order : 34 11 67
In order : 11 34 67
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
24
 
Post order : 24 11 67 34
Pre order : 34 11 24 67
In order : 11 24 34 67
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
6
 
Post order : 6 24 11 67 34
Pre order : 34 11 6 24 67
In order : 6 11 24 34 67
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
97
 
Post order : 6 24 11 97 67 34
Pre order : 34 11 6 24 67 97
In order : 6 11 24 34 67 97
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
12
 
Post order : 6 12 24 11 97 67 34
Pre order : 34 11 6 24 12 67 97
In order : 6 11 12 24 34 67 97
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
1
Enter integer element to insert
57
 
Post order : 6 12 24 11 57 97 67 34
Pre order : 34 11 6 24 12 67 57 97
In order : 6 11 12 24 34 57 67 97
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
2
Nodes = 8
 
Post order : 6 12 24 11 57 97 67 34
Pre order : 34 11 6 24 12 67 57 97
In order : 6 11 12 24 34 57 67 97
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
3
Enter integer element to search
57
Search result : true
 
Post order : 6 12 24 11 57 97 67 34
Pre order : 34 11 6 24 12 67 57 97
In order : 6 11 12 24 34 57 67 97
Do you want to continue (Type y or n)
 
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
5
 
Tree cleared
 
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
y
 
ScapeGoat Tree Operations
 
1. insert
2. count nodes
3. search
4. check empty
5. make empty
4
Empty status = true
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.