SlideShare uma empresa Scribd logo
1 de 15
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow
duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == null && root.right == null) {
return 1;
}
// If the root has children, we recursively count the number of leaf nodes in both the
// left and right subtrees and return the sum
return countLeafNodes(root.left) + countLeafNodes(root.right);
}
/**
* Checks if the tree is a full tree.
*
* @param t The root of the tree.
* @return
*/
private boolean isFull(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so it is not full
if (root == null) {
return false;
}
// If the root has no children, it means the tree only has one node, which makes it a full tree
if (root.left == null && root.right == null) {
return true;
}
// If the root has only one child, it is not a full tree
if (root.left == null || root.right == null) {
return false;
}
// If the root has two children, we recursively check both the left and right subtrees
// to see if they are both full
return isFull(root.left) && isFull(root.right);
}
public void insert(AnyType x) {
root = insert(x, root);
}
/**
* Counts the number of leaf nodes in a tree.
*
* @return
*/
public int countLeafNodes() {
return countLeafNodes(root);
}
/**
* Checks if the tree is full.
*
* @return
*/
public boolean isFull() {
return isFull(root);
}
/**
* Remove from the tree. Nothing is done if x is not found.
*
* @param x the item to remove.
*/
public void remove(AnyType x) {
root = remove(x, root);
}
/**
* Internal method to remove from a subtree.
*
* @param x the item to remove.
* @param root the node that roots the subtree.
* @return the new root of the subtree.
*/
protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> root) {
// If item not found, do nothing.
if (root == null) {
return root;
}
int compareResult = x.compareTo(root.element);
if (compareResult < 0) {
root.left = remove(x, root.left);
} else if (compareResult > 0) {
root.right = remove(x, root.right);
} // Two children.
else if (root.left != null && root.right != null) {
root.element = findMin(root.right).element;
root.right = remove(root.element, root.right);
} // Zero or one child.
else {
root = (root.left != null) ? root.left : root.right;
}
return root;
}
/**
* Find an item in the tree.
*
* @param x the item to search for.
* @return true if not found.
*/
public boolean contains(AnyType x) {
return contains(x, root);
}
private boolean contains(AnyType x, BinaryNode<AnyType> root) {
if (root == null) {
return false;
}
int compareResult = x.compareTo(root.element);
if (compareResult < 0) {
return contains(x, root.left);
} else if (compareResult > 0) {
return contains(x, root.right);
} else {
return true; // Match with current node
}
}
/**
* Find the smallest item in the tree.
*
* @return smallest item or null if empty.
* @throws Exception
*/
public AnyType findMin() throws Exception {
if (isEmpty()) {
throw new Exception();
}
return findMin(root).element;
}
private BinaryNode<AnyType> findMin(BinaryNode<AnyType> root) {
if (root == null) {
return null;
} else if (root.left == null) {
return root; // found the leftmost node
} else {
return findMin(root.left);
}
}
/**
* Test if the tree is logically empty.
*
* @return true if empty, false otherwise.
*/
public boolean isEmpty() {
return root == null;
}
/**
* Calculate the height of the tree.
*
* @return the height.
*/
public int height() {
return height(this.root);
}
/**
* Internal method to compute height of a subtree.
*
* @param root the node that roots the subtree.
* @return
*/
protected int height(BinaryNode<AnyType> root) {
return root == null ? -1
: 1 + Math.max(height(root.left), height(root.right));
}
public BinaryNode<AnyType> getRoot() {
return root;
}
public void setRoot(BinaryNode<AnyType> root) {
this.root = root;
}
public void printSideways(String label) {
System.out.println(
"n-------------------------------" + label + "----------------------------");
printSideways(root, "");
}
private void printSideways(BinaryNode root,
String indent) {
if (root != null) {
printSideways(root.right, indent + " ");
System.out.println(indent + root.element);
printSideways(root.left, indent + " ");
}
}
}
public class AVLTree<AnyType extends Comparable<? super AnyType>> extends
BinarySearchTree<AnyType> {
public AVLTree() {
super();
this.BALANCE_FACTOR = 1;
}
private final int BALANCE_FACTOR;
/**
*
* @param root The root of the BST
* @return The balanced tree.
*/
private BinaryNode<AnyType> balance(BinaryNode<AnyType> root) {
if (root == null) {
return root;
}
private BinaryNode<AnyType> balance(BinaryNode<AnyType> root) {
if (root == null) {
return root;
}
int heightDiff = height(root.left) - height(root.right);
if (heightDiff > BALANCE_FACTOR) {
// case 1: left-left
if (height(root.left.left) >= height(root.left.right)) {
root = rotateRightWithLeftChild(root);
}
// case 2: left-right
else {
root = doubleLeftRight(root);
}
} else if (heightDiff < -BALANCE_FACTOR) {
// case 3: right-right
if (height(root.right.right) >= height(root.right.left)) {
root = rotateLeftWithRightChild(root);
}
// case 4: right-left
else {
root = doubleRightLeft(root);
}
}
return root;
}
return root;
}
/**
* Rotate binary tree node with left child. For AVL trees, this is a single
* rotation for case 1.
*/
private BinaryNode<AnyType> rotateRightWithLeftChild(BinaryNode<AnyType> k2) {
BinaryNode<AnyType> k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
}
/**
* Rotate binary tree node with right child. For AVL trees, this is a single
* rotation for case 4.
*/
private BinaryNode<AnyType> rotateLeftWithRightChild(BinaryNode<AnyType> k1) {
BinaryNode<AnyType> k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
}
/**
* Double rotate binary tree node: first left child with its right child;
* then node k3 with new left child. For AVL trees, this is a double
* rotation for case 2.
*/
private BinaryNode<AnyType> doubleLeftRight(BinaryNode<AnyType> k3) {
k3.left = rotateLeftWithRightChild(k3.left);
return rotateRightWithLeftChild(k3);
}
/**
* Double rotate binary tree node: first right child with its left child;
* then node k1 with new right child. For AVL trees, this is a double
* rotation for case 3.
*/
private BinaryNode<AnyType> doubleRightLeft(BinaryNode<AnyType> k1) {
k1.right = rotateRightWithLeftChild(k1.right);
return rotateLeftWithRightChild(k1);
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
*/
@Override
public void insert(AnyType x) {
root = insert(x, root);
}
/**
* Internal method to insert into a subtree.
*
* @param x the item to insert.
* @param root the node that roots the subtree.
* @return the new root of the subtree.
*/
@Override
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
return balance(super.insert(x, root));
}
/**
* Remove from the tree. Nothing is done if x is not found.
*
* @param x the item to remove.
*/
@Override
public void remove(AnyType x) {
root = remove(x, root);
}
/**
* Internal method to remove from a subtree.
*
* @param x the item to remove.
* @param root the node that roots the subtree.
* @return the new root of the subtree.
*/
@Override
protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> root) {
return balance(super.remove(x, root));
}
public void checkBalance() {
checkBalance(root);
}
private int checkBalance(BinaryNode<AnyType> root) {
if (root == null) {
return -1;
} else {
int heightLeft = checkBalance(root.left);
int heightRight = checkBalance(root.right);
if (Math.abs(height(root.left) - height(root.right)) > BALANCE_FACTOR
|| height(root.left) != heightLeft || height(root.right) != heightRight) {
System.out.println("!!!!!!UNBALANCED TREE!!!!!!");
}
}
return height(root);
}
}

Mais conteúdo relacionado

Semelhante a Once you have all the structures working as intended- it is time to co.docx

A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
 
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdfarihantmobileselepun
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdferremmfab
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfhadpadrrajeshh
 
For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfxlynettalampleyxc
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfarchiesgallery
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
 
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfsivakumar19831
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdffcaindore
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
 
Please i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdfPlease i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdfezzi552
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdffederaleyecare
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfFootageetoffe16
 
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdframbagra74
 

Semelhante a Once you have all the structures working as intended- it is time to co.docx (20)

A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
 
For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdf
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdf
 
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdf
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
 
Please i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdfPlease i need help on following program using C++ Language.Add the.pdf
Please i need help on following program using C++ Language.Add the.pdf
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
 

Mais de farrahkur54

PARTICIPANTS PROFILE ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CARE.docx
PARTICIPANTS PROFILE  ANSWER ABOVE MENTIONED QUESTIONS  BY TAKING CARE.docxPARTICIPANTS PROFILE  ANSWER ABOVE MENTIONED QUESTIONS  BY TAKING CARE.docx
PARTICIPANTS PROFILE ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CARE.docxfarrahkur54
 
Part3- Offline traffic monitoring In this part will use a PCAP file to.docx
Part3- Offline traffic monitoring In this part will use a PCAP file to.docxPart3- Offline traffic monitoring In this part will use a PCAP file to.docx
Part3- Offline traffic monitoring In this part will use a PCAP file to.docxfarrahkur54
 
Participation is a requirement of this course- Students provide one po.docx
Participation is a requirement of this course- Students provide one po.docxParticipation is a requirement of this course- Students provide one po.docx
Participation is a requirement of this course- Students provide one po.docxfarrahkur54
 
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docx
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docxPartners Johnny and Daniel each have capital balances of $95-000- Migu.docx
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docxfarrahkur54
 
Parthians- write one to two paragraphs on the significance of this ite.docx
Parthians- write one to two paragraphs on the significance of this ite.docxParthians- write one to two paragraphs on the significance of this ite.docx
Parthians- write one to two paragraphs on the significance of this ite.docxfarrahkur54
 
Overview You are required to prepare a Data Entry report which provide.docx
Overview You are required to prepare a Data Entry report which provide.docxOverview You are required to prepare a Data Entry report which provide.docx
Overview You are required to prepare a Data Entry report which provide.docxfarrahkur54
 
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
package edu-ser222-m03_02-   ---  - A binary search tree based impleme.docxpackage edu-ser222-m03_02-   ---  - A binary search tree based impleme.docx
package edu-ser222-m03_02- --- - A binary search tree based impleme.docxfarrahkur54
 
P(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docx
P(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docxP(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docx
P(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docxfarrahkur54
 
Overton Company has gathered the following information-Compute equival.docx
Overton Company has gathered the following information-Compute equival.docxOverton Company has gathered the following information-Compute equival.docx
Overton Company has gathered the following information-Compute equival.docxfarrahkur54
 
Option #1- Form Validation in JavaScript 1- In your text editor- open.docx
Option #1- Form Validation in JavaScript 1- In your text editor- open.docxOption #1- Form Validation in JavaScript 1- In your text editor- open.docx
Option #1- Form Validation in JavaScript 1- In your text editor- open.docxfarrahkur54
 
Over 1 million Americans make a living working for advertising and pub.docx
Over 1 million Americans make a living working for advertising and pub.docxOver 1 million Americans make a living working for advertising and pub.docx
Over 1 million Americans make a living working for advertising and pub.docxfarrahkur54
 
Oscar is suing John for $1000 dollars but the judge sees that their ar.docx
Oscar is suing John for $1000 dollars but the judge sees that their ar.docxOscar is suing John for $1000 dollars but the judge sees that their ar.docx
Oscar is suing John for $1000 dollars but the judge sees that their ar.docxfarrahkur54
 
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docx
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docxOrganizational Behavior Chapter 5 - Perception and Indigidual Decision.docx
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docxfarrahkur54
 
ook at the mean- median- mode- and standard deviation and describe how.docx
ook at the mean- median- mode- and standard deviation and describe how.docxook at the mean- median- mode- and standard deviation and describe how.docx
ook at the mean- median- mode- and standard deviation and describe how.docxfarrahkur54
 
Option #1- Creating a GUI Bank Balance Application Create a simple Gr.docx
Option #1-  Creating a GUI Bank Balance Application Create a simple Gr.docxOption #1-  Creating a GUI Bank Balance Application Create a simple Gr.docx
Option #1- Creating a GUI Bank Balance Application Create a simple Gr.docxfarrahkur54
 
Operational Metrics and Benchmarking in Healthcare- What are common op.docx
Operational Metrics and Benchmarking in Healthcare- What are common op.docxOperational Metrics and Benchmarking in Healthcare- What are common op.docx
Operational Metrics and Benchmarking in Healthcare- What are common op.docxfarrahkur54
 
One of the duties and functions of the joint OHS committee is to ensur.docx
One of the duties and functions of the joint OHS committee is to ensur.docxOne of the duties and functions of the joint OHS committee is to ensur.docx
One of the duties and functions of the joint OHS committee is to ensur.docxfarrahkur54
 
One of the deadliest heart conditions is a disturbance in heart rhythm.docx
One of the deadliest heart conditions is a disturbance in heart rhythm.docxOne of the deadliest heart conditions is a disturbance in heart rhythm.docx
One of the deadliest heart conditions is a disturbance in heart rhythm.docxfarrahkur54
 

Mais de farrahkur54 (20)

PARTICIPANTS PROFILE ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CARE.docx
PARTICIPANTS PROFILE  ANSWER ABOVE MENTIONED QUESTIONS  BY TAKING CARE.docxPARTICIPANTS PROFILE  ANSWER ABOVE MENTIONED QUESTIONS  BY TAKING CARE.docx
PARTICIPANTS PROFILE ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CARE.docx
 
Part3- Offline traffic monitoring In this part will use a PCAP file to.docx
Part3- Offline traffic monitoring In this part will use a PCAP file to.docxPart3- Offline traffic monitoring In this part will use a PCAP file to.docx
Part3- Offline traffic monitoring In this part will use a PCAP file to.docx
 
Participation is a requirement of this course- Students provide one po.docx
Participation is a requirement of this course- Students provide one po.docxParticipation is a requirement of this course- Students provide one po.docx
Participation is a requirement of this course- Students provide one po.docx
 
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docx
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docxPartners Johnny and Daniel each have capital balances of $95-000- Migu.docx
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docx
 
Parthians- write one to two paragraphs on the significance of this ite.docx
Parthians- write one to two paragraphs on the significance of this ite.docxParthians- write one to two paragraphs on the significance of this ite.docx
Parthians- write one to two paragraphs on the significance of this ite.docx
 
P(X-x).docx
P(X-x).docxP(X-x).docx
P(X-x).docx
 
Overview You are required to prepare a Data Entry report which provide.docx
Overview You are required to prepare a Data Entry report which provide.docxOverview You are required to prepare a Data Entry report which provide.docx
Overview You are required to prepare a Data Entry report which provide.docx
 
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
package edu-ser222-m03_02-   ---  - A binary search tree based impleme.docxpackage edu-ser222-m03_02-   ---  - A binary search tree based impleme.docx
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
 
P(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docx
P(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docxP(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docx
P(A)+P(A)-1 is one way to express the P(A)+P(A)-1 is one way to expres.docx
 
P(Z-0-86).docx
P(Z-0-86).docxP(Z-0-86).docx
P(Z-0-86).docx
 
Overton Company has gathered the following information-Compute equival.docx
Overton Company has gathered the following information-Compute equival.docxOverton Company has gathered the following information-Compute equival.docx
Overton Company has gathered the following information-Compute equival.docx
 
Option #1- Form Validation in JavaScript 1- In your text editor- open.docx
Option #1- Form Validation in JavaScript 1- In your text editor- open.docxOption #1- Form Validation in JavaScript 1- In your text editor- open.docx
Option #1- Form Validation in JavaScript 1- In your text editor- open.docx
 
Over 1 million Americans make a living working for advertising and pub.docx
Over 1 million Americans make a living working for advertising and pub.docxOver 1 million Americans make a living working for advertising and pub.docx
Over 1 million Americans make a living working for advertising and pub.docx
 
Oscar is suing John for $1000 dollars but the judge sees that their ar.docx
Oscar is suing John for $1000 dollars but the judge sees that their ar.docxOscar is suing John for $1000 dollars but the judge sees that their ar.docx
Oscar is suing John for $1000 dollars but the judge sees that their ar.docx
 
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docx
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docxOrganizational Behavior Chapter 5 - Perception and Indigidual Decision.docx
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docx
 
ook at the mean- median- mode- and standard deviation and describe how.docx
ook at the mean- median- mode- and standard deviation and describe how.docxook at the mean- median- mode- and standard deviation and describe how.docx
ook at the mean- median- mode- and standard deviation and describe how.docx
 
Option #1- Creating a GUI Bank Balance Application Create a simple Gr.docx
Option #1-  Creating a GUI Bank Balance Application Create a simple Gr.docxOption #1-  Creating a GUI Bank Balance Application Create a simple Gr.docx
Option #1- Creating a GUI Bank Balance Application Create a simple Gr.docx
 
Operational Metrics and Benchmarking in Healthcare- What are common op.docx
Operational Metrics and Benchmarking in Healthcare- What are common op.docxOperational Metrics and Benchmarking in Healthcare- What are common op.docx
Operational Metrics and Benchmarking in Healthcare- What are common op.docx
 
One of the duties and functions of the joint OHS committee is to ensur.docx
One of the duties and functions of the joint OHS committee is to ensur.docxOne of the duties and functions of the joint OHS committee is to ensur.docx
One of the duties and functions of the joint OHS committee is to ensur.docx
 
One of the deadliest heart conditions is a disturbance in heart rhythm.docx
One of the deadliest heart conditions is a disturbance in heart rhythm.docxOne of the deadliest heart conditions is a disturbance in heart rhythm.docx
One of the deadliest heart conditions is a disturbance in heart rhythm.docx
 

Último

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Último (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Once you have all the structures working as intended- it is time to co.docx

  • 1. Once you have all the structures working as intended, it is time to compare the performances of the 2. Use runBenchmark() to start. a. First, generate an increasing number (N) of random integers (1000, 5000, 10000, 50000, 75000, 100000, 500000 or as far as your computing power will let you) i. Time and print how long it takes to insert the random integers into an initially empty BST. Do not print the tree. You can get a random list using the java class Random, located in java.util.Random. To test the speed of the insertion algorithm, you should use the System.currentTimeMillis() method, which returns a long that contains the current time (in milliseconds). Call System.currentTimeMillis() before and after the algorithm runs and subtract the two times. (Instant.now() is an alternative way of recording the time.) ii. Time and print how long it takes to insert the same random integers into an initially empty AVL tree. Do not print the tree. iii. If T(N) is the time function, how does the growth of TBST(N) compare with the growth of TAVL(N)? Plot a simple graph to of time against N for the two types of BSTs to visualize your results. b. Second, generate a list of k random integers. k is also some large value. i. Time how long it takes to search your various N-node BSTs for all k random integers. It does not matter whether the search succeeds. ii. Time how long it takes to search your N-node AVL trees for the same k random integers. iii. Compare the growth rates of these two search time-functions with a graph the same way you did in part a. public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> { protected BinaryNode<AnyType> root; public BinarySearchTree() {
  • 2. root = null; } /** * Insert into the tree; duplicates are ignored. * * @param x the item to insert. * @param root * @return */ protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) { // If the root is null, we've reached an empty leaf node, so we create a new node // with the value x and return it if (root == null) { return new BinaryNode<>(x, null, null); } // Compare the value of x to the value stored in the root node int compareResult = x.compareTo(root.element); // If x is less than the value stored in the root node, we insert it into the left subtree if (compareResult < 0) { root.left = insert(x, root.left); } // If x is greater than the value stored in the root node, we insert it into the right subtree else if (compareResult > 0) {
  • 3. root.right = insert(x, root.right); } // If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates return root; } /** * Counts the number of leaf nodes in this tree. * * @param t The root of the tree. * @return */ private int countLeafNodes(BinaryNode<AnyType> root) { // If the root is null, it means the tree is empty, so we return 0 if (root == null) { return 0; } // If the root has no children, it means it is a leaf node, so we return 1 if (root.left == null && root.right == null) { return 1; } // If the root has children, we recursively count the number of leaf nodes in both the // left and right subtrees and return the sum return countLeafNodes(root.left) + countLeafNodes(root.right);
  • 4. } /** * Checks if the tree is a full tree. * * @param t The root of the tree. * @return */ private boolean isFull(BinaryNode<AnyType> root) { // If the root is null, it means the tree is empty, so it is not full if (root == null) { return false; } // If the root has no children, it means the tree only has one node, which makes it a full tree if (root.left == null && root.right == null) { return true; } // If the root has only one child, it is not a full tree if (root.left == null || root.right == null) { return false; } // If the root has two children, we recursively check both the left and right subtrees // to see if they are both full return isFull(root.left) && isFull(root.right);
  • 5. } public void insert(AnyType x) { root = insert(x, root); } /** * Counts the number of leaf nodes in a tree. * * @return */ public int countLeafNodes() { return countLeafNodes(root); } /** * Checks if the tree is full. * * @return */ public boolean isFull() { return isFull(root); } /** * Remove from the tree. Nothing is done if x is not found. *
  • 6. * @param x the item to remove. */ public void remove(AnyType x) { root = remove(x, root); } /** * Internal method to remove from a subtree. * * @param x the item to remove. * @param root the node that roots the subtree. * @return the new root of the subtree. */ protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> root) { // If item not found, do nothing. if (root == null) { return root; } int compareResult = x.compareTo(root.element); if (compareResult < 0) { root.left = remove(x, root.left); } else if (compareResult > 0) { root.right = remove(x, root.right); } // Two children.
  • 7. else if (root.left != null && root.right != null) { root.element = findMin(root.right).element; root.right = remove(root.element, root.right); } // Zero or one child. else { root = (root.left != null) ? root.left : root.right; } return root; } /** * Find an item in the tree. * * @param x the item to search for. * @return true if not found. */ public boolean contains(AnyType x) { return contains(x, root); } private boolean contains(AnyType x, BinaryNode<AnyType> root) { if (root == null) { return false; } int compareResult = x.compareTo(root.element);
  • 8. if (compareResult < 0) { return contains(x, root.left); } else if (compareResult > 0) { return contains(x, root.right); } else { return true; // Match with current node } } /** * Find the smallest item in the tree. * * @return smallest item or null if empty. * @throws Exception */ public AnyType findMin() throws Exception { if (isEmpty()) { throw new Exception(); } return findMin(root).element; } private BinaryNode<AnyType> findMin(BinaryNode<AnyType> root) { if (root == null) { return null;
  • 9. } else if (root.left == null) { return root; // found the leftmost node } else { return findMin(root.left); } } /** * Test if the tree is logically empty. * * @return true if empty, false otherwise. */ public boolean isEmpty() { return root == null; } /** * Calculate the height of the tree. * * @return the height. */ public int height() { return height(this.root); } /**
  • 10. * Internal method to compute height of a subtree. * * @param root the node that roots the subtree. * @return */ protected int height(BinaryNode<AnyType> root) { return root == null ? -1 : 1 + Math.max(height(root.left), height(root.right)); } public BinaryNode<AnyType> getRoot() { return root; } public void setRoot(BinaryNode<AnyType> root) { this.root = root; } public void printSideways(String label) { System.out.println( "n-------------------------------" + label + "----------------------------"); printSideways(root, ""); } private void printSideways(BinaryNode root, String indent) { if (root != null) {
  • 11. printSideways(root.right, indent + " "); System.out.println(indent + root.element); printSideways(root.left, indent + " "); } } } public class AVLTree<AnyType extends Comparable<? super AnyType>> extends BinarySearchTree<AnyType> { public AVLTree() { super(); this.BALANCE_FACTOR = 1; } private final int BALANCE_FACTOR; /** * * @param root The root of the BST * @return The balanced tree. */ private BinaryNode<AnyType> balance(BinaryNode<AnyType> root) { if (root == null) { return root; } private BinaryNode<AnyType> balance(BinaryNode<AnyType> root) { if (root == null) { return root; } int heightDiff = height(root.left) - height(root.right); if (heightDiff > BALANCE_FACTOR) { // case 1: left-left
  • 12. if (height(root.left.left) >= height(root.left.right)) { root = rotateRightWithLeftChild(root); } // case 2: left-right else { root = doubleLeftRight(root); } } else if (heightDiff < -BALANCE_FACTOR) { // case 3: right-right if (height(root.right.right) >= height(root.right.left)) { root = rotateLeftWithRightChild(root); } // case 4: right-left else { root = doubleRightLeft(root); } } return root; } return root; } /** * Rotate binary tree node with left child. For AVL trees, this is a single * rotation for case 1. */ private BinaryNode<AnyType> rotateRightWithLeftChild(BinaryNode<AnyType> k2) {
  • 13. BinaryNode<AnyType> k1 = k2.left; k2.left = k1.right; k1.right = k2; return k1; } /** * Rotate binary tree node with right child. For AVL trees, this is a single * rotation for case 4. */ private BinaryNode<AnyType> rotateLeftWithRightChild(BinaryNode<AnyType> k1) { BinaryNode<AnyType> k2 = k1.right; k1.right = k2.left; k2.left = k1; return k2; } /** * Double rotate binary tree node: first left child with its right child; * then node k3 with new left child. For AVL trees, this is a double * rotation for case 2. */ private BinaryNode<AnyType> doubleLeftRight(BinaryNode<AnyType> k3) { k3.left = rotateLeftWithRightChild(k3.left); return rotateRightWithLeftChild(k3); } /** * Double rotate binary tree node: first right child with its left child; * then node k1 with new right child. For AVL trees, this is a double * rotation for case 3. */ private BinaryNode<AnyType> doubleRightLeft(BinaryNode<AnyType> k1) { k1.right = rotateRightWithLeftChild(k1.right); return rotateLeftWithRightChild(k1); } /** * Insert into the tree; duplicates are ignored.
  • 14. * * @param x the item to insert. */ @Override public void insert(AnyType x) { root = insert(x, root); } /** * Internal method to insert into a subtree. * * @param x the item to insert. * @param root the node that roots the subtree. * @return the new root of the subtree. */ @Override protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) { return balance(super.insert(x, root)); } /** * Remove from the tree. Nothing is done if x is not found. * * @param x the item to remove. */ @Override public void remove(AnyType x) { root = remove(x, root); } /** * Internal method to remove from a subtree. * * @param x the item to remove. * @param root the node that roots the subtree. * @return the new root of the subtree. */ @Override protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> root) { return balance(super.remove(x, root)); } public void checkBalance() { checkBalance(root); }
  • 15. private int checkBalance(BinaryNode<AnyType> root) { if (root == null) { return -1; } else { int heightLeft = checkBalance(root.left); int heightRight = checkBalance(root.right); if (Math.abs(height(root.left) - height(root.right)) > BALANCE_FACTOR || height(root.left) != heightLeft || height(root.right) != heightRight) { System.out.println("!!!!!!UNBALANCED TREE!!!!!!"); } } return height(root); } }