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

DOCX
Once you have all the structures working as intended- it is time to co.docx
PDF
A perfect left-sided binary tree is a binary tree where every intern.pdf
DOCX
Required to augment the authors Binary Search Tree (BST) code to .docx
PDF
I have a .java program that I need to modify so that it1) reads i.pdf
PDF
JavaCreate a java application using the code example in the follo.pdf
PDF
Given the following codepackage data1;import java.util.;p.pdf
PDF
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
PDF
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
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
Required to augment the authors Binary Search Tree (BST) code to .docx
I have a .java program that I need to modify so that it1) reads i.pdf
JavaCreate a java application using the code example in the follo.pdf
Given the following codepackage data1;import java.util.;p.pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf

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

DOCX
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
PDF
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
PDF
TO DO add your implementation and JavaDocs.public class ThreeT.pdf
DOCX
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
PDF
How to do the main method for this programBinaryNode.javapublic.pdf
PDF
It is the main program that implement the min(), max(), floor(), cei.pdf
PDF
in this assignment you are asked to write a simple driver program an.pdf
PDF
BSTNode.Java Node class used for implementing the BST. .pdf
DOCX
For this project, write a program that stores integers in a binary.docx
PDF
package DataStructures; public class HelloWorld AnyType extends.pdf
PDF
For the code below complete the preOrder() method so that it perform.pdf
PDF
Tree Leetcode - Interview Questions - Easy Collections
PDF
Count Red Nodes. Write a program that computes the percentage of red.pdf
PDF
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
PDF
To create a node for a binary search tree (BTNode, ) and to create a .pdf
PDF
Here is the code given in the instructionsclass AVL {.pdf
DOCX
Please finish everything marked TODO BinaryNode-java public class Bi.docx
DOCX
Write a program that displays an AVL tree along with its balance fact.docx
PDF
write a method to generate AVL tree of height h wth fewest nodes and.pdf
DOCX
Write a program that displays an AVL tree along with its balance fac.docx
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
TO DO add your implementation and JavaDocs.public class ThreeT.pdf
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
How to do the main method for this programBinaryNode.javapublic.pdf
It is the main program that implement the min(), max(), floor(), cei.pdf
in this assignment you are asked to write a simple driver program an.pdf
BSTNode.Java Node class used for implementing the BST. .pdf
For this project, write a program that stores integers in a binary.docx
package DataStructures; public class HelloWorld AnyType extends.pdf
For the code below complete the preOrder() method so that it perform.pdf
Tree Leetcode - Interview Questions - Easy Collections
Count Red Nodes. Write a program that computes the percentage of red.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
To create a node for a binary search tree (BTNode, ) and to create a .pdf
Here is the code given in the instructionsclass AVL {.pdf
Please finish everything marked TODO BinaryNode-java public class Bi.docx
Write a program that displays an AVL tree along with its balance fact.docx
write a method to generate AVL tree of height h wth fewest nodes and.pdf
Write a program that displays an AVL tree along with its balance fac.docx
Ad

More from flashfashioncasualwe (20)

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

Recently uploaded (20)

PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
RMMM.pdf make it easy to upload and study
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Cell Types and Its function , kingdom of life
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Insiders guide to clinical Medicine.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pre independence Education in Inndia.pdf
Anesthesia in Laparoscopic Surgery in India
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
RMMM.pdf make it easy to upload and study
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
O5-L3 Freight Transport Ops (International) V1.pdf
human mycosis Human fungal infections are called human mycosis..pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Computing-Curriculum for Schools in Ghana
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Cell Types and Its function , kingdom of life
STATICS OF THE RIGID BODIES Hibbelers.pdf
01-Introduction-to-Information-Management.pdf
Microbial disease of the cardiovascular and lymphatic systems
Module 4: Burden of Disease Tutorial Slides S2 2025
Insiders guide to clinical Medicine.pdf

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. } }