SlideShare a Scribd company logo
1 of 7
Download to read offline
Add to BST.java a method height() that computes the height of the tree. Develop two
implementations: a recursive method (which takes linear time and space proportional to the
height), and method like size() that adds a field to each node in the tree (and takes linear space
and constant time per query)
Solution
Answer:
/*BST.java a method height() that computes the height of the tree. Developing two
implementations: a recursive method, and method like size() that adds a field to each node in the
tree **/
public class SplayBST, Value> {
private Node root; // root of the BST
// BST helper node data type
private class Node {
private Key key; // key
private Value value; // associated data
private Node left, right; // left and right subtrees
public Node(Key key, Value value) {
this.key = key;
this.value = value;
}
}
public boolean contains(Key key) {
return get(key) != null;
}
// return value associated with the given key
// if no such value, return null
public Value get(Key key) {
root = splay(root, key);
int cmp = key.compareTo(root.key);
if (cmp == 0) return root.value;
else return null;
}
/*
* Splay tree insertion.
**/
public void put(Key key, Value value) {
// splay key to root
if (root == null) {
root = new Node(key, value);
return;
}
root = splay(root, key);
int cmp = key.compareTo(root.key);
// Insert new node at root
if (cmp < 0) {
Node n = new Node(key, value);
n.left = root.left;
n.right = root;
root.left = null;
root = n;
}
// Insert new node at root
else if (cmp > 0) {
Node n = new Node(key, value);
n.right = root.right;
n.left = root;
root.right = null;
root = n;
}
// It was a duplicate key. Simply replace the value
else {
root.value = value;
}
}
/*
* Splay tree deletion.
**/
/*
*This splays the key, then does a slightly modified Hibbard deletion on the root (if it is the node
to be deleted, if it is not, the key was not in the tree).
*The modification is that rather than swapping the root (call it node A) with its successor, it's
successor (call it Node B) is moved to the root position
*by splaying for the deletion key in A's right subtree. Finally, A's right child is made the new
root's right child.
*/
public void remove(Key key) {
if (root == null) return; // empty tree
root = splay(root, key);
int cmp = key.compareTo(root.key);
if (cmp == 0) {
if (root.left == null) {
root = root.right;
}
else {
Node x = root.right;
root = root.left;
splay(root, key);
root.right = x;
}
}
// else: it wasn't in the tree to remove
}
/*
* Splay tree function.
**/
// splay key in the tree rooted at Node h. If a node with that key exists,
// it is splayed to the root of the tree. If it does not, the last node
// along the search path for the key is splayed to the root.
private Node splay(Node h, Key key) {
if (h == null) return null;
int cmp1 = key.compareTo(h.key);
if (cmp1 < 0) {
// key not in tree, so we're done
if (h.left == null) {
return h;
}
int cmp2 = key.compareTo(h.left.key);
if (cmp2 < 0) {
h.left.left = splay(h.left.left, key);
h = rotateRight(h);
}
else if (cmp2 > 0) {
h.left.right = splay(h.left.right, key);
if (h.left.right != null)
h.left = rotateLeft(h.left);
}
if (h.left == null) return h;
else return rotateRight(h);
}
else if (cmp1 > 0) {
// key not in tree, so we're done
if (h.right == null) {
return h;
}
int cmp2 = key.compareTo(h.right.key);
if (cmp2 < 0) {
h.right.left = splay(h.right.left, key);
if (h.right.left != null)
h.right = rotateRight(h.right);
}
else if (cmp2 > 0) {
h.right.right = splay(h.right.right, key);
h = rotateLeft(h);
}
if (h.right == null) return h;
else return rotateLeft(h);
}
else return h;
}
/*
* Helper functions.
**/
// height of tree (1-node tree has height 0)
public int height() { return height(root); }
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
public int size() {
return size(root);
}
private int size(Node x) {
if (x == null) return 0;
else return 1 + size(x.left) + size(x.right);
}
// right rotate
private Node rotateRight(Node h) {
Node x = h.left;
h.left = x.right;
x.right = h;
return x;
}
// left rotate
private Node rotateLeft(Node h) {
Node x = h.right;
h.right = x.left;
x.left = h;
return x;
}
// test client
public static void main(String[] args) {
SplayBST st1 = new SplayBST();
st1.put(5, 5);
st1.put(9, 9);
st1.put(13, 13);
st1.put(11, 11);
st1.put(1, 1);
SplayBST st = new SplayBST();
st.put("www.cs.princeton.edu", "128.112.136.11");
st.put("www.cs.princeton.edu", "128.112.136.12");
st.put("www.cs.princeton.edu", "128.112.136.13");
st.put("www.princeton.edu", "128.112.128.15");
st.put("www.yale.edu", "130.132.143.21");
st.put("www.simpsons.com", "209.052.165.60");
StdOut.println("The size 0 is: " + st.size());
st.remove("www.yale.edu");
StdOut.println("The size 1 is: " + st.size());
st.remove("www.princeton.edu");
StdOut.println("The size 2 is: " + st.size());
st.remove("non-member");
StdOut.println("The size 3 is: " + st.size());
StdOut.println(st.get("www.cs.princeton.edu"));
StdOut.println("The size 4 is: " + st.size());
StdOut.println(st.get("www.yale.com"));
StdOut.println("The size 5 is: " + st.size());
StdOut.println(st.get("www.simpsons.com"));
StdOut.println("The size 6 is: " + st.size());
StdOut.println();
}
}

More Related Content

Similar to Add to BST.java a method height() that computes the height of the tr.pdf

Define a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdfDefine a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdfeyelineoptics
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfallystraders
 
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
 
#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
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6m0bz
 
Python Spell Checker
Python Spell CheckerPython Spell Checker
Python Spell CheckerAmr Alarabi
 
I need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfI need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfmail931892
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
 
It is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdfIt is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdfannaindustries
 
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
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docxajoy21
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
Tree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfTree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
 
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
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdffeelingcomputors
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureZarghamullahShah
 
Im having trouble implementing a delete function for an AVL tree. .pdf
Im having trouble implementing a delete function for an AVL tree. .pdfIm having trouble implementing a delete function for an AVL tree. .pdf
Im having trouble implementing a delete function for an AVL tree. .pdfsktambifortune
 

Similar to Add to BST.java a method height() that computes the height of the tr.pdf (20)

Define a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdfDefine a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdf
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdf
 
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
 
#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
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6
 
Python Spell Checker
Python Spell CheckerPython Spell Checker
Python Spell Checker
 
I need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfI need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdf
 
08 binarysearchtrees 1
08 binarysearchtrees 108 binarysearchtrees 1
08 binarysearchtrees 1
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
 
It is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.pdfIt is the main program that implement the min(), max(), floor(), cei.pdf
It is the main program that implement the min(), max(), floor(), cei.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
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docx
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
Tree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfTree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdf
 
Leftlist Heap-1.pdf
Leftlist Heap-1.pdfLeftlist Heap-1.pdf
Leftlist Heap-1.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
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
Im having trouble implementing a delete function for an AVL tree. .pdf
Im having trouble implementing a delete function for an AVL tree. .pdfIm having trouble implementing a delete function for an AVL tree. .pdf
Im having trouble implementing a delete function for an AVL tree. .pdf
 

More from flashfashioncasualwe

How does the mutation rate of speciation in the Dobzhansky- Muller m.pdf
How does the mutation rate of speciation in the Dobzhansky- Muller m.pdfHow does the mutation rate of speciation in the Dobzhansky- Muller m.pdf
How does the mutation rate of speciation in the Dobzhansky- Muller m.pdfflashfashioncasualwe
 
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfHello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfflashfashioncasualwe
 
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdf
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdfFocus on Writing 4. Supporting a Point of View Do you think Social Se.pdf
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdfflashfashioncasualwe
 
Decision-Making Across the Organization The board of trustees of a lo.pdf
Decision-Making Across the Organization The board of trustees of a lo.pdfDecision-Making Across the Organization The board of trustees of a lo.pdf
Decision-Making Across the Organization The board of trustees of a lo.pdfflashfashioncasualwe
 
Explain the experience of African-Americans in the South over the co.pdf
Explain the experience of African-Americans in the South over the co.pdfExplain the experience of African-Americans in the South over the co.pdf
Explain the experience of African-Americans in the South over the co.pdfflashfashioncasualwe
 
During a diversity management session, a manager suggests that stereo.pdf
During a diversity management session, a manager suggests that stereo.pdfDuring a diversity management session, a manager suggests that stereo.pdf
During a diversity management session, a manager suggests that stereo.pdfflashfashioncasualwe
 
Explain why a mycoplasma PCR kit might give a negative result when u.pdf
Explain why a mycoplasma PCR kit might give a negative result when u.pdfExplain why a mycoplasma PCR kit might give a negative result when u.pdf
Explain why a mycoplasma PCR kit might give a negative result when u.pdfflashfashioncasualwe
 
Describe the difference between the MOV instruction and the LEA instr.pdf
Describe the difference between the MOV instruction and the LEA instr.pdfDescribe the difference between the MOV instruction and the LEA instr.pdf
Describe the difference between the MOV instruction and the LEA instr.pdfflashfashioncasualwe
 
Explain how enzymes work, explaining the four major types of metabol.pdf
Explain how enzymes work, explaining the four major types of metabol.pdfExplain how enzymes work, explaining the four major types of metabol.pdf
Explain how enzymes work, explaining the four major types of metabol.pdfflashfashioncasualwe
 
Develop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdfDevelop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdfflashfashioncasualwe
 
Describe one event from your daily life when you have changed your o.pdf
Describe one event from your daily life when you have changed your o.pdfDescribe one event from your daily life when you have changed your o.pdf
Describe one event from your daily life when you have changed your o.pdfflashfashioncasualwe
 
All answers must be in your own wordsProvide a good, understandabl.pdf
All answers must be in your own wordsProvide a good, understandabl.pdfAll answers must be in your own wordsProvide a good, understandabl.pdf
All answers must be in your own wordsProvide a good, understandabl.pdfflashfashioncasualwe
 
C programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdfC programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdfflashfashioncasualwe
 
Write an awareness objective for a newly formed adolescent chemical .pdf
Write an awareness objective for a newly formed adolescent chemical .pdfWrite an awareness objective for a newly formed adolescent chemical .pdf
Write an awareness objective for a newly formed adolescent chemical .pdfflashfashioncasualwe
 
which of these prokaryotes are most likely to be found in the immedi.pdf
which of these prokaryotes are most likely to be found in the immedi.pdfwhich of these prokaryotes are most likely to be found in the immedi.pdf
which of these prokaryotes are most likely to be found in the immedi.pdfflashfashioncasualwe
 
2. Why is only one end point observed for citric acid even though it .pdf
2. Why is only one end point observed for citric acid even though it .pdf2. Why is only one end point observed for citric acid even though it .pdf
2. Why is only one end point observed for citric acid even though it .pdfflashfashioncasualwe
 
10. Benefits and costs of International Trade Search for a newspap.pdf
10. Benefits and costs of International Trade  Search for a newspap.pdf10. Benefits and costs of International Trade  Search for a newspap.pdf
10. Benefits and costs of International Trade Search for a newspap.pdfflashfashioncasualwe
 
Why does the pattern in a shift register shift only one bit position.pdf
Why does the pattern in a shift register shift only one bit position.pdfWhy does the pattern in a shift register shift only one bit position.pdf
Why does the pattern in a shift register shift only one bit position.pdfflashfashioncasualwe
 
Use the Internet to identify three network firewalls, and create a t.pdf
Use the Internet to identify three network firewalls, and create a t.pdfUse the Internet to identify three network firewalls, and create a t.pdf
Use the Internet to identify three network firewalls, and create a t.pdfflashfashioncasualwe
 
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdf
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdfTo vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdf
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdfflashfashioncasualwe
 

More from flashfashioncasualwe (20)

How does the mutation rate of speciation in the Dobzhansky- Muller m.pdf
How does the mutation rate of speciation in the Dobzhansky- Muller m.pdfHow does the mutation rate of speciation in the Dobzhansky- Muller m.pdf
How does the mutation rate of speciation in the Dobzhansky- Muller m.pdf
 
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfHello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
 
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdf
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdfFocus on Writing 4. Supporting a Point of View Do you think Social Se.pdf
Focus on Writing 4. Supporting a Point of View Do you think Social Se.pdf
 
Decision-Making Across the Organization The board of trustees of a lo.pdf
Decision-Making Across the Organization The board of trustees of a lo.pdfDecision-Making Across the Organization The board of trustees of a lo.pdf
Decision-Making Across the Organization The board of trustees of a lo.pdf
 
Explain the experience of African-Americans in the South over the co.pdf
Explain the experience of African-Americans in the South over the co.pdfExplain the experience of African-Americans in the South over the co.pdf
Explain the experience of African-Americans in the South over the co.pdf
 
During a diversity management session, a manager suggests that stereo.pdf
During a diversity management session, a manager suggests that stereo.pdfDuring a diversity management session, a manager suggests that stereo.pdf
During a diversity management session, a manager suggests that stereo.pdf
 
Explain why a mycoplasma PCR kit might give a negative result when u.pdf
Explain why a mycoplasma PCR kit might give a negative result when u.pdfExplain why a mycoplasma PCR kit might give a negative result when u.pdf
Explain why a mycoplasma PCR kit might give a negative result when u.pdf
 
Describe the difference between the MOV instruction and the LEA instr.pdf
Describe the difference between the MOV instruction and the LEA instr.pdfDescribe the difference between the MOV instruction and the LEA instr.pdf
Describe the difference between the MOV instruction and the LEA instr.pdf
 
Explain how enzymes work, explaining the four major types of metabol.pdf
Explain how enzymes work, explaining the four major types of metabol.pdfExplain how enzymes work, explaining the four major types of metabol.pdf
Explain how enzymes work, explaining the four major types of metabol.pdf
 
Develop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdfDevelop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdf
 
Describe one event from your daily life when you have changed your o.pdf
Describe one event from your daily life when you have changed your o.pdfDescribe one event from your daily life when you have changed your o.pdf
Describe one event from your daily life when you have changed your o.pdf
 
All answers must be in your own wordsProvide a good, understandabl.pdf
All answers must be in your own wordsProvide a good, understandabl.pdfAll answers must be in your own wordsProvide a good, understandabl.pdf
All answers must be in your own wordsProvide a good, understandabl.pdf
 
C programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdfC programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdf
 
Write an awareness objective for a newly formed adolescent chemical .pdf
Write an awareness objective for a newly formed adolescent chemical .pdfWrite an awareness objective for a newly formed adolescent chemical .pdf
Write an awareness objective for a newly formed adolescent chemical .pdf
 
which of these prokaryotes are most likely to be found in the immedi.pdf
which of these prokaryotes are most likely to be found in the immedi.pdfwhich of these prokaryotes are most likely to be found in the immedi.pdf
which of these prokaryotes are most likely to be found in the immedi.pdf
 
2. Why is only one end point observed for citric acid even though it .pdf
2. Why is only one end point observed for citric acid even though it .pdf2. Why is only one end point observed for citric acid even though it .pdf
2. Why is only one end point observed for citric acid even though it .pdf
 
10. Benefits and costs of International Trade Search for a newspap.pdf
10. Benefits and costs of International Trade  Search for a newspap.pdf10. Benefits and costs of International Trade  Search for a newspap.pdf
10. Benefits and costs of International Trade Search for a newspap.pdf
 
Why does the pattern in a shift register shift only one bit position.pdf
Why does the pattern in a shift register shift only one bit position.pdfWhy does the pattern in a shift register shift only one bit position.pdf
Why does the pattern in a shift register shift only one bit position.pdf
 
Use the Internet to identify three network firewalls, and create a t.pdf
Use the Internet to identify three network firewalls, and create a t.pdfUse the Internet to identify three network firewalls, and create a t.pdf
Use the Internet to identify three network firewalls, and create a t.pdf
 
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdf
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdfTo vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdf
To vaccinate or not to vaccinate Is the influenza Virus vaccine Saf.pdf
 

Recently uploaded

會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxCeline George
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxLimon Prince
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 

Recently uploaded (20)

會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 

Add to BST.java a method height() that computes the height of the tr.pdf

  • 1. Add to BST.java a method height() that computes the height of the tree. Develop two implementations: a recursive method (which takes linear time and space proportional to the height), and method like size() that adds a field to each node in the tree (and takes linear space and constant time per query) Solution Answer: /*BST.java a method height() that computes the height of the tree. Developing two implementations: a recursive method, and method like size() that adds a field to each node in the tree **/ public class SplayBST, Value> { private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value value; // associated data private Node left, right; // left and right subtrees public Node(Key key, Value value) { this.key = key; this.value = value; } } public boolean contains(Key key) { return get(key) != null; } // return value associated with the given key // if no such value, return null public Value get(Key key) { root = splay(root, key); int cmp = key.compareTo(root.key); if (cmp == 0) return root.value; else return null; } /*
  • 2. * Splay tree insertion. **/ public void put(Key key, Value value) { // splay key to root if (root == null) { root = new Node(key, value); return; } root = splay(root, key); int cmp = key.compareTo(root.key); // Insert new node at root if (cmp < 0) { Node n = new Node(key, value); n.left = root.left; n.right = root; root.left = null; root = n; } // Insert new node at root else if (cmp > 0) { Node n = new Node(key, value); n.right = root.right; n.left = root; root.right = null; root = n; } // It was a duplicate key. Simply replace the value else { root.value = value; } } /* * Splay tree deletion.
  • 3. **/ /* *This splays the key, then does a slightly modified Hibbard deletion on the root (if it is the node to be deleted, if it is not, the key was not in the tree). *The modification is that rather than swapping the root (call it node A) with its successor, it's successor (call it Node B) is moved to the root position *by splaying for the deletion key in A's right subtree. Finally, A's right child is made the new root's right child. */ public void remove(Key key) { if (root == null) return; // empty tree root = splay(root, key); int cmp = key.compareTo(root.key); if (cmp == 0) { if (root.left == null) { root = root.right; } else { Node x = root.right; root = root.left; splay(root, key); root.right = x; } } // else: it wasn't in the tree to remove } /* * Splay tree function. **/ // splay key in the tree rooted at Node h. If a node with that key exists, // it is splayed to the root of the tree. If it does not, the last node // along the search path for the key is splayed to the root.
  • 4. private Node splay(Node h, Key key) { if (h == null) return null; int cmp1 = key.compareTo(h.key); if (cmp1 < 0) { // key not in tree, so we're done if (h.left == null) { return h; } int cmp2 = key.compareTo(h.left.key); if (cmp2 < 0) { h.left.left = splay(h.left.left, key); h = rotateRight(h); } else if (cmp2 > 0) { h.left.right = splay(h.left.right, key); if (h.left.right != null) h.left = rotateLeft(h.left); } if (h.left == null) return h; else return rotateRight(h); } else if (cmp1 > 0) { // key not in tree, so we're done if (h.right == null) { return h; } int cmp2 = key.compareTo(h.right.key); if (cmp2 < 0) { h.right.left = splay(h.right.left, key); if (h.right.left != null) h.right = rotateRight(h.right); } else if (cmp2 > 0) { h.right.right = splay(h.right.right, key); h = rotateLeft(h);
  • 5. } if (h.right == null) return h; else return rotateLeft(h); } else return h; } /* * Helper functions. **/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } public int size() { return size(root); } private int size(Node x) { if (x == null) return 0; else return 1 + size(x.left) + size(x.right); } // right rotate private Node rotateRight(Node h) { Node x = h.left; h.left = x.right; x.right = h; return x; } // left rotate private Node rotateLeft(Node h) {
  • 6. Node x = h.right; h.right = x.left; x.left = h; return x; } // test client public static void main(String[] args) { SplayBST st1 = new SplayBST(); st1.put(5, 5); st1.put(9, 9); st1.put(13, 13); st1.put(11, 11); st1.put(1, 1); SplayBST st = new SplayBST(); st.put("www.cs.princeton.edu", "128.112.136.11"); st.put("www.cs.princeton.edu", "128.112.136.12"); st.put("www.cs.princeton.edu", "128.112.136.13"); st.put("www.princeton.edu", "128.112.128.15"); st.put("www.yale.edu", "130.132.143.21"); st.put("www.simpsons.com", "209.052.165.60"); StdOut.println("The size 0 is: " + st.size()); st.remove("www.yale.edu"); StdOut.println("The size 1 is: " + st.size()); st.remove("www.princeton.edu"); StdOut.println("The size 2 is: " + st.size()); st.remove("non-member"); StdOut.println("The size 3 is: " + st.size()); StdOut.println(st.get("www.cs.princeton.edu")); StdOut.println("The size 4 is: " + st.size()); StdOut.println(st.get("www.yale.com")); StdOut.println("The size 5 is: " + st.size()); StdOut.println(st.get("www.simpsons.com")); StdOut.println("The size 6 is: " + st.size()); StdOut.println();
  • 7. } }