Question

Create a set of 100,000 integers. Insert these integers to (i) an AVL tree, (ii) the original red...

Create a set of 100,000 integers. Insert these integers to (i) an AVL tree, (ii) the original red,-black tree, and (iii) the modified red black tree. Repeat this step about 6 times with different sets of integers, and report the mean, maximum and minimum values of the following. For (i) and (ii), you can either write the algorithms on your own or use algorithms obtained from elsewhere.

1. The height of the completed tree

2. The black height ( give the maximum black height if the black height is not the same in all the

paths)

3. The time to create the tree

1 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.*;
import java.util.*;

public class AVLTree {
    public class Node {
        private Node left, right, parent;
        private int height = 1;
        private int value;

        private Node (int val) {
            this.value = val;
        }
    }
    private int height (Node N) {
        if (N == null)
            return 0;
        return N.height;
    }

    private Node insert(Node node, int value) {
        /* 1.  Perform the normal BST rotation */
        if (node == null) {
            return(new Node(value));
        }

        if (value < node.value)
            node.left  = insert(node.left, value);
        else
            node.right = insert(node.right, value);

        /* 2. Update height of this ancestor node */
        node.height = Math.max(height(node.left), height(node.right)) + 1;

        /* 3. Get the balance factor of this ancestor node to check whether
           this node became unbalanced */
        int balance = getBalance(node);

        // If this node becomes unbalanced, then there are 4 cases

        // Left Left Case
        if (balance > 1 && value < node.left.value)
            return rightRotate(node);

        // Right Right Case
        if (balance < -1 && value > node.right.value)
            return leftRotate(node);

        // Left Right Case
        if (balance > 1 && value > node.left.value)
        {
            node.left =  leftRotate(node.left);
            return rightRotate(node);
        }

        // Right Left Case
        if (balance < -1 && value < node.right.value)
        {
            node.right = rightRotate(node.right);
            return leftRotate(node);
        }

        /* return the (unchanged) node pointer */
        return node;
    }

    private Node rightRotate(Node y) {
        Node x = y.left;
        Node T2 = x.right;

        // Perform rotation
        x.right = y;
        y.left = T2;

        // Update heights
        y.height = Math.max(height(y.left), height(y.right))+1;
        x.height = Math.max(height(x.left), height(x.right))+1;

        // Return new root
        return x;
    }

    private Node leftRotate(Node x) {
        Node y = x.right;
        Node T2 = y.left;

        // Perform rotation
        y.left = x;
        x.right = T2;

        //  Update heights
        x.height = Math.max(height(x.left), height(x.right))+1;
        y.height = Math.max(height(y.left), height(y.right))+1;

        // Return new root
        return y;
    }

    // Get Balance factor of node N
    private int getBalance(Node N) {
        if (N == null)
            return 0;
        return height(N.left) - height(N.right);
    }

    public void preOrder(Node root) {
        if (root != null) {
            preOrder(root.left);
            System.out.printf("%d ", root.value);
            preOrder(root.right);
        }
    }

    private Node minValueNode(Node node) {
        Node current = node;
        /* loop down to find the leftmost leaf */
        while (current.left != null)
            current = current.left;
        return current;
    }

    private Node deleteNode(Node root, int value) {
        // STEP 1: PERFORM STANDARD BST DELETE

        if (root == null)
            return root;

        // If the value to be deleted is smaller than the root's value,
        // then it lies in left subtree
        if ( value < root.value )
            root.left = deleteNode(root.left, value);

        // If the value to be deleted is greater than the root's value,
        // then it lies in right subtree
        else if( value > root.value )
            root.right = deleteNode(root.right, value);

        // if value is same as root's value, then This is the node
        // to be deleted
        else {
            // node with only one child or no child
            if( (root.left == null) || (root.right == null) ) {

                Node temp;
                if (root.left != null)
                        temp = root.left;
                else
                    temp = root.right;

                // No child case
                if(temp == null) {
                    temp = root;
                    root = null;
                }
                else // One child case
                    root = temp; // Copy the contents of the non-empty child

                temp = null;
            }
            else {
                // node with two children: Get the inorder successor (smallest
                // in the right subtree)
                Node temp = minValueNode(root.right);

                // Copy the inorder successor's data to this node
                root.value = temp.value;

                // Delete the inorder successor
                root.right = deleteNode(root.right, temp.value);
            }
        }

        // If the tree had only one node then return
        if (root == null)
            return root;

        // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
        root.height = Math.max(height(root.left), height(root.right)) + 1;

        // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
        //  this node became unbalanced)
        int balance = getBalance(root);

        // If this node becomes unbalanced, then there are 4 cases

        // Left Left Case
        if (balance > 1 && getBalance(root.left) >= 0)
            return rightRotate(root);

        // Left Right Case
        if (balance > 1 && getBalance(root.left) < 0) {
            root.left =  leftRotate(root.left);
            return rightRotate(root);
        }

        // Right Right Case
        if (balance < -1 && getBalance(root.right) <= 0)
            return leftRotate(root);

        // Right Left Case
        if (balance < -1 && getBalance(root.right) > 0) {
            root.right = rightRotate(root.right);
            return leftRotate(root);
        }

        return root;
    }

    public void print(Node root) {

        if(root == null) {
            System.out.println("(XXXXXX)");
            return;
        }

        int height = root.height,
            width = (int)Math.pow(2, height-1);

        // Preparing variables for loop.
        List<Node> current = new ArrayList<Node>(1),
            next = new ArrayList<Node>(2);
        current.add(root);

        final int maxHalfLength = 4;
        int elements = 1;

        StringBuilder sb = new StringBuilder(maxHalfLength*width);
        for(int i = 0; i < maxHalfLength*width; i++)
            sb.append(' ');
        String textBuffer;

        // Iterating through height levels.
        for(int i = 0; i < height; i++) {

            sb.setLength(maxHalfLength * ((int)Math.pow(2, height-1-i) - 1));

            // Creating spacer space indicator.
            textBuffer = sb.toString();

            // Print tree node elements
            for(Node n : current) {

                System.out.print(textBuffer);

                if(n == null) {

                    System.out.print("        ");
                    next.add(null);
                    next.add(null);

                } else {

                    System.out.printf("(%6d)", n.value);
                    next.add(n.left);
                    next.add(n.right);

                }

                System.out.print(textBuffer);

            }

            System.out.println();
            // Print tree node extensions for next level.
            if(i < height - 1) {

                for(Node n : current) {

                    System.out.print(textBuffer);

                    if(n == null)
                        System.out.print("        ");
                    else
                        System.out.printf("%s      %s",
                                n.left == null ? " " : "/", n.right == null ? " " : "\\");

                    System.out.print(textBuffer);

                }

                System.out.println();

            }

            // Renewing indicators for next run.
            elements *= 2;
            current = next;
            next = new ArrayList<Node>(elements);

        }

    }

    public static void main(String args[]) {
        AVLTree t = new AVLTree();
        Node root = null;
        while (true) {
            System.out.println("(1) Insert");
            System.out.println("(2) Delete");

            try {
                BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
                String s = bufferRead.readLine();

                if (Integer.parseInt(s) == 1) {
                    System.out.print("Value to be inserted: ");
                    root = t.insert(root, Integer.parseInt(bufferRead.readLine()));
                }
                else if (Integer.parseInt(s) == 2) {
                    System.out.print("Value to be deleted: ");
                    root = t.deleteNode(root, Integer.parseInt(bufferRead.readLine()));
                }
                else {
                    System.out.println("Invalid choice, try again!");
                    continue;
                }

                t.print(root);
            }
            catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Add a comment
Know the answer?
Add Answer to:
Create a set of 100,000 integers. Insert these integers to (i) an AVL tree, (ii) the original red...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • IN C++: Create sets of 1 Million integer, where no integer is repeated. Insert these numbers...

    IN C++: Create sets of 1 Million integer, where no integer is repeated. Insert these numbers to an (i) AVL tree and (ii) R-B tree. Compute the time taken to insert all the numbers. Repeat the experiment 10 times, each time regenerating the set. In a table report (a) the time taken to complete the insertion (b) the height of the tree, (c) the black height of the R-B Tree

  • Create sets of integers with the following characteristics with array sizes of 100,000, 500,000 and 1000,000...

    Create sets of integers with the following characteristics with array sizes of 100,000, 500,000 and 1000,000 1. Set where no integer is repeated 2. Set where the range is low and the integers repeat Compare the performances of the following sorting algorithms. You can either write the algorithms on your own or modify algorithms obtained from elsewhere. Create a table with the rows being the different algorithms and the columns being the inputs. Run each input 10 times and report...

  • PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a...

    PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a class called MyTree with the methods __init__(x), getLeft(), getRight(), getData(), insert(x) and getHeight(). Each child should itself be a MyTree object. The height of a leaf node should be zero. The insert(x) method should return the node that occupies the original node's position in the tree. Create a class called MyBST that extends MyTree. Override the method insert(x) to meet the definitions of a...

  • 1.find the following i. Use histogram equalization to improve the contrast of an image of your...

    1.find the following i. Use histogram equalization to improve the contrast of an image of your choice. Explain why the contrast changed (or didn’t change). Show both the original and modified image and a histogram for both images. ii. Convert a color image of your choice to black and white. Then, convert the black and white image to a binary image. Repeat the previous step, but use a different threshold value. Share both the original, the black and white image,...

  • Part B (BI). Implement a Red-Black tree with only operation Insert(). Your program should read from...

    Part B (BI). Implement a Red-Black tree with only operation Insert(). Your program should read from a file that contain positive integers and should insert those numbers into the RB tree in that order. Note that the input file will only contain distinct integers. Print your tree by level using positive values for Black color and negative values for Red color Do not print out null nodes. Format for a node: <Node_value>, <Parent_value>). For example, the following tree is represented...

  • The ACME Manufacturing Company has hired you to help automate their production assembly line. Cameras have...

    The ACME Manufacturing Company has hired you to help automate their production assembly line. Cameras have been placed above a conveyer belt to enables parts on the belt to be photographed and analyzed. You are to augment the system that has been put in place by writing C code to detect the number of parts on the belt, and the positions of each object. The process by which you will do this is called Connected Component Labeling (CCL). These positions...

  • In a new file located in the same package as the class Main, create a public...

    In a new file located in the same package as the class Main, create a public Java class to represent a photograph that consists of a linear (not 2D) array of pixels. Each pixel is stored as an integer. The photograph class must have: (a) Two private fields to represent the information stored about the photograph. These are the array of integers and the date the photograph was taken (stored as a String). The values in the array must be...

  • I need help with research critique summary of this below article in APA format and in...

    I need help with research critique summary of this below article in APA format and in text citation and the reference en/poni%20perception%20article.pdf EATING DISORDERS 2018, VOL. 26, NO. 2, 107-126 https://doi.org/10.1080/10640266,2017.1318624 Routledge Taylor & Francis Group PREVENTION SERIES Check to Perceptions of disordered eating and associated help seeking in young women Annamaria J. McAndrew and Rosanne Menna Department of Psychology, University of Windsor, Windsor, Ontario, Canada ABSTRACT Disordered eating is common among young women, but rates of help-seeking are remarkably...

  • 10. The Beck & Watson article is a Group of answer choices quantitative study qualitative study...

    10. The Beck & Watson article is a Group of answer choices quantitative study qualitative study 11. Beck & Watson examined participants' experiences and perceptions using what type of research design? Group of answer choices particpant obersvation phenomenology 12. Select the participants in the Beck & Watson study Group of answer choices Caucasian women with 2-4 children Caucasian pregnant women 13. In the Beck & Watson study, data was collected via a(n) Group of answer choices internet study focus group...

  • 14. Select the number of participants in the Beck & Watson study Group of answer choices...

    14. Select the number of participants in the Beck & Watson study Group of answer choices 8 13 22 35 15. Beck & Watson determined their final sample size via Group of answer choices coding saturation triangulation ethnography 16.Through their study, Beck & Watson determined Group of answer choices after a traumatic birth, subsequent births have no troubling effects after a traumatic birth, subsequent births brought fear, terror, anxiety, and dread Subsequent Childbirth After a Previous Traumatic Birth Beck, Cheryl...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT