SlideShare a Scribd company logo
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);
}
}

More Related Content

Similar to 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.pdf
michardsonkhaicarr37
 
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
adityastores21
 
(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
arihantmobileselepun
 
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
erremmfab
 
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
hadpadrrajeshh
 
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
xlynettalampleyxc
 
#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
ajoy21
 
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
archiesgallery
 
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
wasemanivytreenrco51
 
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
sivakumar19831
 
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
ajaycosmeticslg
 
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
fcaindore
 
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
anton291
 
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
ezzi552
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
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
federaleyecare
 
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
rohit219406
 
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
JUSTSTYLISH3B2MOHALI
 
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
Footageetoffe16
 
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
rambagra74
 

Similar to 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
 

More from 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.docx
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
P(X-x).docx
P(X-x).docxP(X-x).docx
P(X-x).docx
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
P(Z-0-86).docx
P(Z-0-86).docxP(Z-0-86).docx
P(Z-0-86).docx
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 
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
farrahkur54
 

More from 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
 

Recently uploaded

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 

Recently uploaded (20)

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 

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); } }